我正在尝试从我的 Web 应用程序将数据表中的数据插入到 Excel 文件中。按下按钮即可填充数据表并将其插入 Excel 文件。问题是当数据正确插入并且我保存文件然后关闭它时,数据就会消失。它发生在 Excel 文档关闭时。
这是我的代码:
public bool ExportDataTableToExcel(DataTable dt, string filepath)
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
try
{
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the Active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "Data";
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oSheet.Cells[1, 1] = "CustID";
oSheet.Cells[1, 2] = "Alias";
oSheet.Cells[1, 3] = "AdrID";
oSheet.Cells[1, 4] = "Truck Delivery Days";
oSheet.Cells[1, 5] = "Truck Delivery Hours";
oSheet.Cells[1, 6] = "Truck Delivery Type";
oSheet.Cells[1, 7] = "Plane Delivery Days";
oSheet.Cells[1, 8] = "Plane Delivery Hours";
oSheet.Cells[1, 9] = "Plane Delivery Type";
oSheet.Cells[1, 10] = "Other Delivery Days";
oSheet.Cells[1, 11] = "Other Delivery Hours";
oSheet.Cells[1, 12] = "Other Delivery Type";
oSheet.Cells[1, 13] = "Distance to Dealer";
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
oRange = oSheet.Range[oSheet.Cells[1, 1],oSheet.Cells[rowCount, dt.Columns.Count]];
oRange.EntireColumn.AutoFit();
// Save the sheet and close
oSheet = null;
oRange = null;
oWB.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();
}
catch
{
throw;
}
finally
{
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
return true;
}
执行此行后数据消失:
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
有人可以帮我吗?
谢谢