gpt4 book ai didi

c# - 使用 Microsoft.Office.Interop.Excel 导出时我是否正确关闭了 excel 文件

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:48 25 4
gpt4 key购买 nike

我正在使用以下 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();

}

最佳答案

这是我的结束语。

确保在捕捉到所有异常后调用它:

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());
}
}

关于c# - 使用 Microsoft.Office.Interop.Excel 导出时我是否正确关闭了 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21965691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com