rider
rider

Reputation: 11

Excel Program using C# VSTO

I have created C# Excel Addin project, in which I have added a User control to that excel and placing a button in User Control . For the button , the code I have written for the getting data from database to Excel cells(sheet1). But the problem encountered here, when I click on button a new excel sheet (application) is opened and data is populated to to new excel sheet from database. But I want to populate my data from database to existing excel sheet only, but not for new excel sheet. Can you one help me?

I should get data in same excel only not for the new excel sheet. Here my code below:-

worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
app.Visible = true;---- **here i am getting new excel application  and data is getting populated**
worksheet.Name = "Export to Excel";
Excel.Range mycell = Excel.Range)worksheet.get_Range("A1:B1","A1:B1");

int CountColumn = ds.Tables[0].Columns.Count;
int CountRow = ds.Tables[0].Rows.Count;
int col = 0;
int row = 1;
string data = null;
int i = 0;
int j = 0;
for (col = 0; col < CountColumn; col++)
{
    worksheet.Cells[row, col + 1] = ds.Tables[0].Columns[col].ColumnName.ToString();
}

}

Upvotes: 1

Views: 3500

Answers (2)

Brijesh Mishra
Brijesh Mishra

Reputation: 2748

not sure why you are using Excel Application object here i.e app, rather in addin project you must use Globals.ThisAddin.Application.ActiveSheet/ Globals.ThisAddin.Application.ActiveWorkBook to get active sheet/workbook. Incase you do not have access to Globals in your wpf project, the correct way to get it you can find at post Get the excel cell address from a UDF, see if this helps

  var worksheet = Globals.ThisAddin.Application.ActiveSheet
        worksheet.Name = "Export to Excel"; 
        Excel.Range mycell = (Excel.Range)worksheet.get_Range("A1:B1","A1:B1");  
        int CountColumn = ds.Tables[0].Columns.Count; 
        int CountRow = ds.Tables[0].Rows.Count; 
        int col = 0; 
        int row = 1; 
        string data = null; 
        int i = 0; 
        int j = 0; 
        for (col = 0; col < CountColumn; col++) 
        { 
            worksheet.Cells[row, col + 1] = ds.Tables[0].Columns[col].ColumnName.ToString(); 
        } 

Upvotes: 1

Mathias
Mathias

Reputation: 15391

By definition, when you are working with an Excel add-in, Excel IS open already, so there is no point in trying to get a new instance started. As Brijesh mentioned, Excel add-ins give you access to the current Excel instance by using Globals.ThisAddin.Application, and from there you can then access the entire object model.

As an aside, it looks like you are writing your data to the sheet by iterating cell by cell. This is a bad idea if you have lots of data, you should be able to write it in one shot.

Upvotes: 0

Related Questions