我使用Microsoft.interop.Excel.dll
将Excel转换为.pdf。核心代码:
using Microsoft.Office.Interop.Excel;
using ExcelApplicationClass = Microsoft.Office.Interop.Excel.ApplicationClass;
public static bool ExcelToPdf(string sourcePath, string targetPath, out string exmsg)
{
exmsg = string.Empty;
bool result = false;
object missing = Type.Missing;
ExcelApplicationClass applicationClass = null;
Workbook workBook = null;
try
{
applicationClass = new ExcelApplicationClass();
applicationClass.Visible = false;
/* applicationClas*/
workBook = applicationClass.Workbooks.Open(sourcePath);
if (workBook != null)
{
Microsoft.Office.Interop.Excel.Worksheet worksheet = workBook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
//*** if I annotation the block in this if. the code no error occured.
if (worksheet != null)
{
worksheet.PageSetup.Zoom = false;
worksheet.PageSetup.FitToPagesWide = 1;
}
workBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, targetPath, XlFixedFormatQuality.xlQualityMinimum, false, true);
}
result = true;
}
catch (Exception ex)
{
exmsg = ex.Message;
result = false;
}
finally
{
if (workBook != null)
{
workBook.Close(true,missing, missing);
workBook = null;
}
if (applicationClass != null)
{
applicationClass.Quit();
applicationClass = null;
}
}
return result;
}
如果我没有将worksheet.PageSetup's
属性设置为zoom
等,那么该程序运行良好,但如果我设置属性System.Runtime.InteropServices.COMException
将会出现9次。有时候没有错误。
Microsoft Excel 2013
Windows 10
每次杀死Microsoft Excel
进度。