C#将Excel转成PDF的方法
PS:公司的业务中有个超级大的作业就是把OFFICE文档转成PDF,我猜之前没程序猿们,公司那些人应该是一个个手动转。强烈为猿们感叹,帮你们做了这么多事,还在那抱怨....无法满足你们的需求啊;
微软net平台提供了对Office文档非常好的支持;其中有com组件直接集成到了VS中。利用这些API可以快速的免去N多繁琐的工作;
以下代码是翻阅了公司的代码,一个个敲出来的;奉上代码:
usingSystem; usingSystem.Collections.Generic; usingSystem.IO; usingSystem.Linq; usingSystem.Text; usingSystem.Runtime.InteropServices; usingMicrosoft.Office.Interop.Excel; //Office命名空间 namespaceOfficeToPdf { //excel类 classExcelConverter { //构造函数 publicExcelConverter() {} //////转换excel成PDF文档 /// ///原文件路径 /// pdf文件输出路径 /// true成功 publicboolConverterToPdf(string_lstrInputFile,string_lstrOutFile) { Microsoft.Office.Interop.Excel.ApplicationlobjExcelApp=null; Microsoft.Office.Interop.Excel.WorkbookslobjExcelWorkBooks=null; Microsoft.Office.Interop.Excel.WorkbooklobjExcelWorkBook=null; stringlstrTemp=string.Empty; objectlobjMissing=System.Reflection.Missing.Value; try { lobjExcelApp=newMicrosoft.Office.Interop.Excel.Application(); lobjExcelApp.Visible=true; lobjExcelWorkBooks=lobjExcelApp.Workbooks; lobjExcelWorkBook=lobjExcelWorkBooks.Open(_lstrInputFile,true,true,lobjMissing,lobjMissing,lobjMissing,true, lobjMissing,lobjMissing,lobjMissing,lobjMissing,lobjMissing,false,lobjMissing,lobjMissing); //Microsoft.Office.Interop.Excel12.0.0.0之后才有这函数 lstrTemp=System.IO.Path.GetTempPath()+Guid.NewGuid().ToString()+".xls"+(lobjExcelWorkBook.HasVBProject?'m':'x'); //lstrTemp=System.IO.Path.GetTempPath()+Guid.NewGuid().ToString()+".xls"; lobjExcelWorkBook.SaveAs(lstrTemp,Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel4Workbook,Type.Missing,Type.Missing,Type.Missing,false,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,Type.Missing, false,Type.Missing,Type.Missing,Type.Missing); //输出为PDF第一个选项指定转出为PDF,还可以指定为XPS格式 lobjExcelWorkBook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF,_lstrOutFile,Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard,Type.Missing,false,Type.Missing,Type.Missing,false,Type.Missing); lobjExcelWorkBooks.Close(); lobjExcelApp.Quit(); } catch(Exceptionex) { //其他日志操作; returnfalse; } finally{ if(lobjExcelWorkBook!=null) { lobjExcelWorkBook.Close(Type.Missing,Type.Missing,Type.Missing); Marshal.ReleaseComObject(lobjExcelWorkBook); lobjExcelWorkBook=null; } if(lobjExcelWorkBooks!=null) { lobjExcelWorkBooks.Close(); Marshal.ReleaseComObject(lobjExcelWorkBooks); lobjExcelWorkBooks=null; } if(lobjExcelApp!=null) { lobjExcelApp.Quit(); Marshal.ReleaseComObject(lobjExcelApp); lobjExcelApp=null; } //主动激活垃圾回收器,主要是避免超大批量转文档时,内存占用过多,而垃圾回收器并不是时刻都在运行! GC.Collect(); GC.WaitForPendingFinalizers(); } returntrue; } } }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接