如何在C# WinForms中实现Excel文件转PDF功能
C# WinForms Excel 转 PDF 实现方案
在开发C# WinForms应用程序时,如需实现Excel文件转换为PDF格式的需求,可参考如下实现代码:
Microsoft.Office.Interop.Excel.Application execl = new Microsoft.Office.Interop.Excel.Application(); object oMissing = System.Reflection.Missing.Value; FileInfo execlFile = new FileInfo(txtNameFile.Text); execl.Visible = false; execl.ScreenUpdating = false; object filename = (object)execlFile.FullName; Workbook doc = execl.Workbooks.Open(ref filename, ref oMissing , ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing , ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing , ref oMissing, ref oMissing, ref oMissing, ref oMissing); doc.Activate(); object outputFileName = execlFile.FullName.Replace(".Xls", ".pdf"); object fileformat = WdSaveFormat.wdFormatPDF; doc.SaveAs2(ref outputFileName, ref fileformat, ref oMissing, ref oMissing , ref oMissing, ref oMissing, ref oMissing, ref oMissing , ref oMissing, ref oMissing, ref oMissing, ref oMissing , ref oMissing, ref oMissing, ref oMissing, ref oMissing); object savechanges = WdSaveOptions.wdSaveChanges; ((Workbooks)doc).Close(ref savechanges, ref oMissing, ref oMissing); doc = null; ((_Application)execl).Quit(ref oMissing, ref oMissing, ref oMissing); execl = null; MessageBox.Show("The File has been converted to PDF ");
注意事项
- 该方案依赖
Microsoft.Office.Interop.Excel组件,使用前需要在项目中添加对应引用,且运行设备上必须安装微软Office - 原代码中后缀替换仅匹配大写
.Xls格式,如需兼容.xlsx、小写后缀等更多Excel格式,需自行调整替换规则 - 代码中引用的
WdSaveFormat.wdFormatPDF是Word互操作库的枚举值,Excel转PDF建议替换为Excel自带的XlFixedFormatType.xlTypePDF枚举,避免类型不匹配导致的运行错误 - 执行完成后建议额外加COM对象释放逻辑,避免Excel进程后台驻留占用系统资源
内容的提问来源于stack exchange,提问作者Ziad Altaji
相关产品推荐
相关产品推荐

