方法1,调用Microsoft.Office.Interop.Excel,缺点是需要安装excel,不支持.net core
private static bool ExcelToPdfWithExcel(string excelFile, string pdfFile)
{
Microsoft.Office.Interop.Excel.Application application = null;
Microsoft.Office.Interop.Excel.Workbooks workbooks = null;
Microsoft.Office.Interop.Excel.Workbook workbook = null;
try
{
application = new Microsoft.Office.Interop.Excel.Application();
application.Visible = false;
workbooks = application.Workbooks;
workbook = workbooks.Open(excelFile, false, true);
workbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, pdfFile);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (workbook != null)
{
workbook.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
}
if (workbooks != null)
{
workbooks.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
workbooks = null;
}
if (application != null)
{
application.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
application = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
return true;
}
方法2,调用FreeSpire.XLS,缺点是免费版只能转3页pdf
private static bool ExcelToPdfWithFreeSpire(string excelFile, string pdfFile)
{
try
{
Workbook workbook = new Workbook();
workbook.LoadFromFile(excelFile);
workbook.SaveToFile(pdfFile, Spire.Xls.FileFormat.PDF);
//判断是否超过免费版限制,3页pdf
PdfDocument pdfDocument = new PdfDocument(pdfFile);
if (pdfDocument.Pages.Count > 3)
{
pdfDocument.Close();
return false;
}
}
catch (Exception ex)
{
return false;
}
return true;
}
方法3,调用NPOI+iTextSharp,缺点是免费版iTextSharp(itext5)不支持.net core,目前最新版itext7已商用(未亲自试过)
https://blog.csdn.net/weixin_43663915/article/details/86599334
方法4,调用OpenOffice,缺点是服务器需要额外装OpenOffice、Java等,配置多,需要额外打开端口(未亲自试过)
https://blog.csdn.net/qq_37319035/article/details/79225024
方法5,调用WPS(未亲自试过)