使用 Microsoft.Office.Interop.Excel 解析 Excel 文件 - 在内存中挂起 Excel.exe 进程
您好,我使用 Microsoft.Office.Interop.Excel 解析 excel 表。这是我的代码,它将 Excel 表解析为数据表。效果很好。
public static DataTable ImportExcelToDataTable(String path)
{
var app = new Application {Visible = false};
Workbook workBook = app.Workbooks.Open(path, 0, true, 5, "", "",
true, XlPlatform.xlWindows, Type.Missing, false,
false, 0, true, 1, 0);
Sheets sheets = workBook.Worksheets;
var activeSheet = (Worksheet) sheets.Item[1];
Range activeSheetRange = activeSheet.UsedRange;
var dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
for (int i = 1; i <= activeSheetRange.Rows.Count; i++)
{
DataRow dr = dt.NewRow();
for (int j = 1; j <= activeSheetRange.Columns.Count; j++)
{
string value = ((Range) activeSheetRange.Cells[i, j]).Value2.ToString();
dr[j - 1] = value;
}
dt.Rows.Add(dr);
dt.AcceptChanges();
}
app.Quit();
app.Workbooks.Close();
GC.Collect();
return dt;
}
问题我运行应用程序(控制台)调用此方法并关闭控制台应用程序。如果我检查 TaskManager 进程,我会看到 Excel.exe 进程仍在运行。
如果我调用此方法 100 次,内存中就会有 100 个 excel.exe 进程。
这是正常的吗?怎么解决呢。
感谢您的时间与合作
Hi I parse excel table with Microsoft.Office.Interop.Excel. Here is my code which parse excel table to data table. It works good.
public static DataTable ImportExcelToDataTable(String path)
{
var app = new Application {Visible = false};
Workbook workBook = app.Workbooks.Open(path, 0, true, 5, "", "",
true, XlPlatform.xlWindows, Type.Missing, false,
false, 0, true, 1, 0);
Sheets sheets = workBook.Worksheets;
var activeSheet = (Worksheet) sheets.Item[1];
Range activeSheetRange = activeSheet.UsedRange;
var dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
for (int i = 1; i <= activeSheetRange.Rows.Count; i++)
{
DataRow dr = dt.NewRow();
for (int j = 1; j <= activeSheetRange.Columns.Count; j++)
{
string value = ((Range) activeSheetRange.Cells[i, j]).Value2.ToString();
dr[j - 1] = value;
}
dt.Rows.Add(dr);
dt.AcceptChanges();
}
app.Quit();
app.Workbooks.Close();
GC.Collect();
return dt;
}
Problem I run app (Console) invoke this method and close console app. If I check in TaskManager process I see that Excel.exe process is still runing.
If I call this method 100-times I have 100 excel.exe processes in memmory.
It is normal ? How can solve it.
Thank for your time and cooperation
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能需要使用 Marshal.ReleaseComObject - 请参阅 这个问题和这个问题。
You might need to use Marshal.ReleaseComObject - see the answers to this question and this question.