1

In my C# program I use excel add in to write data to an excel file, below is just an example the way I tried to access the excel sheet.

private void button1_Click(object sender, EventArgs e)
{
    Excel.Application xl_app = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    Excel.Workbook xl_workbook = null;
    xl_workbook = xl_app.ActiveWorkbook;
    Excel.Worksheet sheet = null;
    sheet = (Excel.Worksheet)xl_workbook.Worksheets.get_Item("Sheet1");
    sheet.Cells[1, 1] = "Name";
}

 

When I run this I get an error saying "Object reference not set to an instance of an object" for sheet object (I have used these Microsoft.Office.Interop.Excel, Microsoft.Office.Core;). I'm new to C#, can anyone help me with this?

5 Answers 5

0
  sheet = (Excel.Worksheet)xl_workbook.Worksheets.get_Item(1); 
0

This is how I would do it:

private void button1_Click(object sender, EventArgs e)
{
    Excel.Application xlApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    Excel.Workbook xlWorkbook = xlApp.ActiveWorkbook;
    Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];
    xlWorksheet.Cells[1,1] = "Name";
}

I tested it with Visual C# 2010 Express and an open Excel Workbook and it works for me.

0

If you want to use the name of the sheet instead of the index and you use Linq as follow:

var xlSheet = xl_workbook.Cast<_Worksheet>().FirstOrDefault(x => x.Name == "Sheet1")

if the sheet is not found the xlsheet variable will be null

0

No one is answer so the right Answer, i checked it and it worked:

Excel.Worksheet activeWorksheet = ((Excel.Worksheet)Application.ActiveSheet);
Excel.Range firstRow = activeWorksheet.get_Range("A1");
firstRow.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
Excel.Range newFirstRow = activeWorksheet.get_Range("A1");
newFirstRow.Value2 = "This text was added by using code";
0
Excel.Application xlAppToExport = new Excel.Application();
xlAppToExport.Workbooks.Add("");

Excel.Worksheet xlWorkSheetToExport;

xlWorkSheetToExport =(Excel.Worksheet)xlAppToExport.Application.Worksheets.Add();
xlWorkSheetToExport.Name = "customer";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.