如何使用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 ");

不要使用savea方法保存,而是在工作簿上使用ExportAsFixedFormat方法导出为PDF格式:

doc.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputFileName);

另外,我建议不要过度使用对象数据类型,它是一种相当广泛的类型。例如,object outputFileName应该是string outputFileName。如果使用了更具体的数据类型,对于编译器和其他人检查你的代码都更容易。

相关内容

  • 没有找到相关文章

最新更新