简体   繁体   中英

Excel add-in; How to write to an excel sheet

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?

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";
Excel.Application xlAppToExport = new Excel.Application();
xlAppToExport.Workbooks.Add("");

Excel.Worksheet xlWorkSheetToExport;

xlWorkSheetToExport =(Excel.Worksheet)xlAppToExport.Application.Worksheets.Add();
xlWorkSheetToExport.Name = "customer";
  sheet = (Excel.Worksheet)xl_workbook.Worksheets.get_Item(1); 

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM