c# - 如何使用 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 ");
解决方案
不要使用 SaveAs 方法保存,而是使用工作簿上的 ExportAsFixedFormat 方法导出为 PDF 格式:
doc.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputFileName);
另外,我建议不要过度使用对象数据类型,这是一种相当广泛的类型。例如,object outputFileName
应该是string outputFileName
。如果使用更具体的数据类型,编译器和其他人检查您的代码会更容易。
推荐阅读
- c++ - 错误:无效使用非静态成员函数'int test::hotplug_callback(libusb_context*, libusb_device*, libusb_hotplug_event, void*)'
- html - 将引导页面转换为 PDF?
- eventbrite - Eventbrite - 使用 REST API 发布事件
- python - 处理 Unicode 字符
- javascript - 嵌套 for 循环的迭代问题
- c - openssl api 函数参考问题
- vba - 在工作簿/工作表打开时创建持久 ADODB 连接
- python - 如何生成具有预定义概率分布的随机数?
- salesforce - 如何在 Salesforce 中重命名我的 Apex 类名称
- c++ - 使用 GetNetworkParams() 检索网络信息时出错