You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 20:54:02