我在项目中使用excel interop时遇到了一个相当烦人的问题。该项目是一个小程序,可以将所有excel文件放在一个文件夹中,并将它们作为一个打印作业打印出来。我这样做的方法是将xls文件转换为pdf,然后将该pdf合并为一个pdf文件。现在的问题是,每当我将xls文件转换为pdf时。我得到一个弹出窗口,说excel已经停止工作了。
如果我在转换后放置一个长线程睡眠计时器,则不会发生这种情况。这是代码:
private void btnConvert_Click(object sender, EventArgs e)
{
var files = new DirectoryInfo(textBox1.Text).GetFiles("*.xls")
foreach (var file in files)
{
ExportWorkbookToPDF(file.FullName,
textBox1.Text + $@"\{pdfFolder}\" + file.Name.Remove(file.Name.Length - 4));
}
}
private static void ExportWorkbookToPDF(string workbook, string output)
{
if (string.IsNullOrEmpty(workbook) || string.IsNullOrEmpty(output))
{
throw new NullReferenceException("Cannot create PDF copy " +
"from empty workbook.");
}
var excelApplication = new Application();
excelApplication.ScreenUpdating = false;
excelApplication.DisplayAlerts = false;
excelApplication.Visible = false;
Workbook excelWorkbook = excelApplication.Workbooks.Open(workbook);
if (excelWorkbook == null)
{
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
throw new NullReferenceException("Cannot create new excel workbook.");
}
try
{
excelWorkbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF,
output);
}
catch (Exception e)
{
}
finally
{
excelWorkbook.Close();
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
}
}