简体   繁体   English

C#生成Excel文件并写入单元格

[英]C# generating excel file and writing to cells

I am working on a project that runs MySQL queries on DB. 我正在一个在数据库上运行MySQL查询的项目中。 I need to feed out the results to a excel sheet that I will be generating on the fly. 我需要将结果提供给我将即时生成的Excel工作表。 I had started the code, using msdn tutorials as well as information I found on stackoverflow, however running the application leaves me with 我已经使用msdn教程以及在stackoverflow上找到的信息开始了代码,但是运行该应用程序使我

"Object reference not set to an instance of an object." “你调用的对象是空的。”

At this point I just have the basic code started as I wanted to make this work before I started creating the entire spreadsheet in the code. 此时,我只是启动了基本代码,因为我想在开始在代码中创建整个电子表格之前完成这项工作。

                    var excelApp = new Excel.Application();
                    excelApp.Visible = true;
                    Excel.Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
                    ((Excel.Range)workSheet.Cells[1, 1]).Value = "Print Date:";

If I can provide any more info just ask. 如果我可以提供更多信息,请询问。 I greatly appreciate any information or insight you can provide me with! 我非常感谢您可以为我提供的任何信息或见解!

I'd say that workSheet is being set to null as excelApp.ActiveSheet doesn't exist yet. 我想说workSheet被设置为null,因为excelApp.ActiveSheet还不存在。

Here's some code that'll create a worksheet object you can use... 这是一些代码,这些代码将创建您可以使用的工作表对象。

var application = new Application();

var workbooks = application.Workbooks;

var workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);

var worksheets = (Sheets)workbook.Worksheets;

var worksheet = worksheets[1];

A few things to note when working with Excel: 使用Excel时需要注意的几件事:

  • Release every object with System.Runtime.InteropServices.Marshal.ReleaseComObject(object) when you're finished with it. 完成后,使用System.Runtime.InteropServices.Marshal.ReleaseComObject(object)释放每个对象。 If you don't, Excel won't exit when you're done. 否则,完成后Excel将不会退出。
  • Don't use double-dot references (ie, object1.object2.value). 不要使用双点引用(即object1.object2.value)。 If you do you can't release it properly as above. 如果这样做,您将无法如上所述正确释放它。
  • Indexes always start from 1, not 0 (in my experience anyway). 索引总是从1开始,而不是0(以我的经验)。

The reason you get that error is, you have not created any worksheets in the Application. 出现该错误的原因是,您尚未在应用程序中创建任何工作表。 Try doing this. 尝试这样做。

Excel.Worksheet newWorksheet; Excel.Worksheet newWorksheet;

newWorksheet = (Excel.Worksheet)excelApp.Worksheets.Add(); newWorksheet =(Excel.Worksheet)excelApp.Worksheets.Add();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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