excel批量转pdf,并合并成单个pdf文件
很久没写了,补一下
之前用Adobe acrobat 合并,后来老出问题。
自己动手写一个了。
开发用2010,转pdf需要office2010或2013支持,2007不支持,
合并pdf需要itextsharp 支持。
贴代码
private static bool ExcelToPdf2(string sourcePath, string targetPath, ApplicationClass applicationClass) { if (File.Exists(targetPath)) { File.Delete(targetPath); } bool result = false; object missing = Type.Missing; XlFixedFormatType xlTypePDF = XlFixedFormatType.xlTypePDF;//转换成pdf string inputfileName = sourcePath;//需要转格式的文件路径 string outputFileName = targetPath;//转换完成后PDF文件的路径和文件名名称 XlFixedFormatType xlFixedFormatType = xlTypePDF;//导出文件所使用的格式 XlFixedFormatQuality xlFixedFormatQuality = XlFixedFormatQuality.xlQualityStandard;//1.xlQualityStandard:质量标准,2.xlQualityMinimum;最低质量 bool includeDocProperties = true;//如果设置为True,则忽略在发布时设置的任何打印区域。 bool openAfterPublish = false;//发布后不打开 Workbook workbook = applicationClass.Workbooks.Open(inputfileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); if (workbook != null) { workbook.ExportAsFixedFormat(xlFixedFormatType, outputFileName, xlFixedFormatQuality, includeDocProperties, openAfterPublish, missing, missing, missing, missing); } result = true; return result; } private static void AddXls2SinglePDF(string dirName, string outFileName, Document document, PdfWriter writer, PdfContentByte cb, ApplicationClass applicationClass) { foreach (var filename in System.IO.Directory.GetFiles(dirName)) { if (Path.GetExtension(filename).ToLower() == ".xls" || Path.GetExtension(filename).ToLower() == ".xlsx") { ExcelToPdf2(filename, filename + ".pdf", applicationClass); PdfReader reader = new PdfReader(filename + ".pdf"); int iPageNum = reader.NumberOfPages; for (int j = 1; j <= iPageNum; j++) { document.NewPage(); PdfImportedPage newPage = writer.GetImportedPage(reader, j); cb.AddTemplate(newPage, 0, 0); } } } foreach (var dir in System.IO.Directory.GetDirectories(dirName)) { AddXls2SinglePDF(dir, outFileName, document, writer, cb, applicationClass); } } public static void XLSTOSinglePDF(string dirName, string outFileName) { Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outFileName, FileMode.Create)); { document.Open(); PdfContentByte cb = writer.DirectContent; object missing = Type.Missing; Microsoft.Office.Interop.Excel.ApplicationClass applicationClass = null; Workbook workbook = null; try { applicationClass = new Microsoft.Office.Interop.Excel.ApplicationClass(); AddXls2SinglePDF(dirName, outFileName, document, writer, cb, applicationClass); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "错误"); } finally { if (workbook != null) { workbook.Close(true, missing, missing); workbook = null; } if (applicationClass != null) { applicationClass.Quit(); applicationClass = null; } } document.Close(); } }