【发布时间】:2016-04-05 08:08:19
【问题描述】:
我尝试将excel 转换为PDF,我可以转换它。但是在打开该文件时,出现如下错误。
我已经从这个链接中引用了这个链接How do I convert Word files to PDF programmatically?,我可以解决我的 Word 到 PDF 文件转换问题。我不必在服务器上安装 Office 并且我想为 excel 和 PPT 文件做同样的事情。
我的代码:
// Create a new Microsoft Excel application object
Microsoft.Office.Interop.Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application();
// C# doesn't have optional arguments so we'll need a dummy value
object oMissing = System.Reflection.Missing.Value;
excelApplication.Visible = false;
excelApplication.ScreenUpdating = false;
FileInfo ExcelFile = new FileInfo(sourcePath);
// Cast as Object for Excel Open method
Object filename = (Object)ExcelFile.FullName;
// Use the dummy value as a placeholder for optional arguments
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApplication.Workbooks.Open(ExcelFile.FullName, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
object outputFileName = ExcelFile.FullName.Replace(Path.GetFileName(ExcelFile.FullName), Path.GetFileName(targetPath));
object fileFormat = WdSaveFormat.wdFormatPDF;
// Save document into PDF Format
//excelWorkbook.SaveAs(outputFileName);
excelWorkbook.SaveAs(outputFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
// Close the Excel Workbook, but leave the Word application open.
// excelWorkbook has to be cast to type _Document so that it will find the
// correct Close method.
object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
((Microsoft.Office.Interop.Excel.Workbook)excelWorkbook).Close();
excelWorkbook = null;
// Excel has to be cast to type _Application so that it will find
// the correct Quit method.
((Microsoft.Office.Interop.Excel._Application)excelApplication).Quit();
excelWorkbook = null;
注意
我不想使用内置的导出功能来完成此操作。如下我已经有它的代码。这是将excel转换为pdf的工作代码。
Microsoft.Office.Interop.Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
excelWorkbook = excelApplication.Workbooks.Open(sourcePath);
excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, targetPath);
excelWorkbook.Close();
excelApplication.Quit();
excelApplication = null;
请让我知道我在哪里做错了。
【问题讨论】:
标签: c# .net excel pdf asp.net-mvc-5