我使用以下example将数据导出到Excel。
我已修改此代码,以便我可以导出&将它保存到Excel文件,但我不确定我是否正确关闭excel文件,我的第二个问题是如果我这样做,是否需要处理任何垃圾收集等。 , 如果我没有正确或者有更好的方法,请告知我们。
static void DisplayInExcel(DataSet ds)
{
var excelApp = new Excel.Application();
// Make the object visible.
excelApp.Visible = true;
// Create a new, empty workbook and add it to the collection returned
// by property Workbooks. The new workbook becomes the active workbook.
// Add has an optional parameter for specifying a praticular template.
// Because no argument is sent in this example, Add creates a new workbook.
excelApp.Workbooks.Add();
// This example uses a single workSheet.
// Excel._Worksheet workSheet = excelApp.ActiveSheet;
// Earlier versions of C# require explicit casting.
Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
// Establish column headings in cells A1 and B1.
workSheet.Cells[1, "B"] = "Date";
workSheet.Cells[1, "C"] = "Title";
workSheet.Cells[1, "D"] = "Details";
DataTable dt = ds.Tables[0];
var rowIndex = 2; // 1 = header row
foreach (DataRow row in dt.Rows)
{
// rowCount++;
workSheet.Cells[rowIndex, "B"] = row["Date"];
workSheet.Cells[rowIndex, "C"] = row["Title"];
workSheet.Cells[rowIndex, "D"] = row["Description"];
rowIndex++;
}
workSheet.Range["A1", "D" + rowIndex + ""].AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatColor2);
//Coloumn 1
workSheet.Range["A:A"].Cells.Font.Bold = true;
workSheet.Range["A:A"].ColumnWidth = 10;
workSheet.Range["A:A"].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
//Column 2
workSheet.Range["B:B"].ColumnWidth = 14;
workSheet.Range["B:B"].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
//workSheet.Range["A1", "A" + rowIndex + ""].Cells.Font.Bold = true;
((Excel.Range)workSheet.Columns[3]).AutoFit();
((Excel.Range)workSheet.Columns[4]).AutoFit();
string fileName = "Product_Excel.xls";
excelApp.DisplayAlerts = false;
workSheet.SaveAs(HttpContext.Current.Server.MapPath("../"+fileName));
GC.Collect();
GC.WaitForPendingFinalizers();
excelApp.Quit();
}
答案 0 :(得分:0)
这是我的结束语。
确保在捕获所有异常后调用此方法:
try
{
//Use spreadsheet here.
DisplayInExcel(ds)
}
catch
{
//Process errors
}
Close();
以下是结束代码:
public void Close()
{
try
{
if (_workBook == null)
{
return;
}
_workBook.Save();
_workBook.Close(false, FILENAME, null);
Marshal.ReleaseComObject(_workBook);
_excel.Quit();
Marshal.ReleaseComObject(_excel);
_workBook = null;
_excel = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
Logger("All done!");
}
catch (Exception e)
{
Logger("Error in cleanup: " + e.ToString());
}
}