我开发了从excel读取的winform应用程序并将其转换为文本文件。 我使用Microsoft.Office.Interop.Excel库来使用Excel。
这是我的代码:
private Excel.Application excel = null;
private Excel.Sheets sheets = null;
private Excel.Workbook excelWorkbook = null;
private Excel.Workbooks excelWorkbooks = null;
private Excel._Worksheet worksheet = null;
private Excel.Range usedRange = null;
public ExcelFacade() { }
public ExcelFacade(string fileName)
{
excel = new Excel.Application();
excelWorkbooks = excel.Workbooks;
excelWorkbook = excelWorkbooks.Open(fileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
sheets = excelWorkbook.Sheets;
}
使用Excel完成工作后,我调用next方法(来自here):
public void Dispose()
{
foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in sheets)
{
while (Marshal.ReleaseComObject(sheet) != 0) { }
}
excelWorkbook.Close();
excelWorkbooks.Close();
excel.Quit();
var chromeDriverProcesses = Process.GetProcesses().
Where(pr => pr.ProcessName.ToLower().Contains("excel"));
foreach (var process in chromeDriverProcesses)
{
process.Kill();
}
//while (Marshal.ReleaseComObject(usedRange) != 0) { }
//while (Marshal.ReleaseComObject(worksheet) != 0) { }
while (Marshal.ReleaseComObject(sheets) != 0) { }
while (Marshal.ReleaseComObject(excelWorkbook) != 0) { }
while (Marshal.ReleaseComObject(excelWorkbooks) != 0) { }
//while (Marshal.ReleaseComObject(excel.Application) != 0)
//{ }
while (Marshal.ReleaseComObject(excel) != 0) { }
usedRange = null;
worksheet = null;
excelWorkbook = null;
excelWorkbooks = null;
sheets = null;
excel = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
但是,如果我更改excel并重新运行我的应用程序,应用程序不会更新更新的excel,它看起来像是从旧的excel读取的。这种行为看起来像缓存,我不知道如何禁用它。
如果我在代码中更改了某些内容,例如,白色空间,并重建应用程序,它的工作辉煌,并采取正确的Excel文件。 有什么建议吗?
答案 0 :(得分:0)
正如@ vbnet3d所说,使用ClosedXML库解决了所有问题