Npoi生成的Excel
/// <summary> /// excel To PDf /// </summary> /// <param name="excelPath">l源文件路径</param> /// <param name="pdfPath">目的文件路径</param> /// <returns></returns> public static bool ConverterToPdf(string excelPath, string pdfPath) { Application excelApp = null; Workbooks excelWorkBooks = null; Workbook excelWorkBook = null; string lstrTemp = string.Empty; object lobjMissing = System.Reflection.Missing.Value; try { excelApp = new Application(); //hide all excel(appliction) excelApp.Visible = true; excelWorkBooks = excelApp.Workbooks; //打开excel,得到WorkBook对象 excelWorkBook = excelWorkBooks.Open(excelPath, true, true, lobjMissing, lobjMissing, lobjMissing, true, lobjMissing, lobjMissing, lobjMissing, lobjMissing, lobjMissing, false, lobjMissing, lobjMissing); lstrTemp = Path.GetTempPath() + Guid.NewGuid().ToString() + ".xls" + (excelWorkBook.HasVBProject ? 'm' : 'x'); //lstrTemp = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".xls"; excelWorkBook.SaveAs(lstrTemp, XlFileFormat.xlExcel4Workbook, Type.Missing, Type.Missing, Type.Missing, false, XlSaveAsAccessMode.xlNoChange, Type.Missing, false, Type.Missing, Type.Missing, Type.Missing); //输出为PDF excelWorkBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, pdfPath, XlFixedFormatQuality.xlQualityStandard, Type.Missing, false, Type.Missing, Type.Missing, false, Type.Missing); //关闭workbooks excelWorkBooks.Close(); //退出excel excelApp.Quit(); } catch (Exception ex) { //其他日志操作; return false; } finally { if (excelWorkBook != null) { Marshal.ReleaseComObject(excelWorkBook); excelWorkBook = null; } if (excelWorkBooks != null) { excelWorkBooks.Close(); Marshal.ReleaseComObject(excelWorkBooks); excelWorkBooks = null; } if (excelApp != null) { excelApp.Quit(); Marshal.ReleaseComObject(excelApp); excelApp = null; } //删掉转换之前的excel if (File.Exists(excelPath)) { File.Delete(excelPath); } //主动激活垃圾回收器,主要是避免超大批量转文档时,内存占用过多,而垃圾回收器并不是时刻都在运行! GC.Collect(); GC.WaitForPendingFinalizers(); } return true; }
反正就不明绝厉,要注意COM组件的注册。
摘别人的:
https://blog.csdn.net/cyj0531/article/details/53423753
对了,需要安装包。 Microsoft office interop.Excel packages.