C#Application.Excel.Quit由于1行代码而不能正常工作

所以我有以下代码。 如果我注释掉它的工作原理,但它一旦我取消注释行Excel不会正常closures。

我不确定接下来要做什么。 我远离2点的问题,并试图坚持1点。 但是现在我不确定现在要做什么。

代码中的dt是我填充的DataTable。

Excel.Application app = null; Excel.Workbooks books = null; Excel.Workbook book = null; Excel.Sheets sheets = null; Excel.Worksheet sheet = null; Excel.Range range = null; try { app = new Excel.Application(); books = app.Workbooks; book = books.Open(FilePath); sheets = book.Sheets; sheet = book.ActiveSheet; int rcount = 45; UpdateProgressBarMaxMethod(pbAssets, rcount); int i = 0; for (; i < rcount; i++) { //Comment out the below line and it works fine dt.Rows.Add(sheet.Cells[i + 1, 1].Value, sheet.Cells[i + 1, 2].Value, sheet.Cells[i + 1, 3].Value, sheet.Cells[i + 1, 4].Value, sheet.Cells[i + 1, 5].Value, sheet.Cells[i + 1, 6].Value, sheet.Cells[i + 1, 7].Value, sheet.Cells[i + 1, 8].Value, sheet.Cells[i + 1, 9].Value); UpdateProgressBarMethod(pbAssets, i); } UpdateProgressBarMethod(pbAssets, 0); book.Close(); app.Quit(); } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } finally { if (range != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(range); if (sheet != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); if (sheets != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets); if (book != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(book); if (books != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(books); if (app != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(app); } 

你实际上并不遵循两点的规则。 sheet.Cells[i + 1, 2].Value – 这是两个点。 它创build一个Range对象(单元格)的引用。

很明显,创build和清理每个单元格的Range对象是一件痛苦的事情。 此链接显示如何创build一个 Range并将值读入数组。

另一个select就是不要使用Excel.Interop ,因为处理所有这些COM对象的巨大痛苦。

这里有一些EPPlus代码的链接 ,它会在没有COM对象的情况下做同样的事情。 还有一些关于使用命名范围的build议,以便您不必处理所有这些行和列号。

Essential XlsIO可以将数据从Excel导入到Datable 。

示例代码

 //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; //Get as DataTable DataTable datatable = sheet.ExportDataTable(sheet.UsedRange, ExcelExportDataTableOptions.ColumnNames); //Upload to dataset DataSet ds = new DataSet(); ds.Tables.Add(datatable); 

如果您符合条件(less于100万美元的收入),那么整套控件都可以通过社区许可计划免费获得(商业应用程序)。 社区许可证是完整的产品,没有限制或水印。

注意:我为Syncfusion工作。