Excel加载项,如何写入Excel工作表

时间:2012-03-12 02:32:16

标签: c# excel

在我的c#程序中,我使用excel add in将数据写入excel文件,下面只是我试图访问excel表的一个例子。

 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";

        }

当我运行这个时,我得到一个错误,说“对象引用没有设置为对象的实例”对于工作表对象。(我使用了这些Microsoft.Office.Interop.Excel, Microsoft.Office.Core;)我是c#的新手,任何人都可以帮助我,谢谢

5 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

如果您想使用工作表的名称而不是索引,并使用Linq,如下所示:

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

如果找不到工作表,则xlsheet变量将为null

答案 2 :(得分:0)

我就是这样做的:

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";
}

我使用Visual C#2010 Express和一个打开的Excel工作簿进行了测试,它对我有用。

答案 3 :(得分:0)

没有人回答所以正确的答案,我检查了它并且有效:

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";

答案 4 :(得分:0)

Excel.Application xlAppToExport = new Excel.Application();
xlAppToExport.Workbooks.Add("");

Excel.Worksheet xlWorkSheetToExport;

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