spire.xls 操作excel 转换成pdf 并且合并成一个文件
1 | <strong>需要nuget 安装FreeSpire.XLS Free为免费版不会带水印</strong> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | <strong><br><br></strong> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Spire.Xls; using Spire.Pdf; using System.IO; namespace SmooreCommon.Excel { public class SpireHelper { /// <summary> /// excel转换成pdf,路径原路返回 /// </summary> /// <param name="paths">excel物理路径</param> /// <param name="isDelOldFile">是否删除源excel文件</param> /// <returns></returns> public static List< string > ExcelToPdf(List< string > paths, bool isDelOldFile = false ) { List< string > pdfPaths = new List< string >(); if (!paths.HasItems()) return pdfPaths; try { foreach ( var item in paths) { var resPath = ExcelToPdf(item, isDelOldFile); pdfPaths.Add(resPath); } } catch (Exception ex) { throw ex; } return pdfPaths; } /// <summary> /// excel转换成pdf,路径原路返回 /// </summary> /// <param name=""></param> /// <param name="isDelOldFile"></param> /// <returns></returns> public static string ExcelToPdf( string path, bool isDelOldFile = false ) { if (path.IsNullOrEmpty()) return "" ; if (!System.IO.File.Exists(path)) return $ "{path}文件不存在!" ; FileInfo fileInfo = new FileInfo(path); var pdfName = fileInfo.Name.Replace(fileInfo.Extension, "" ) + ".pdf" ; var dirName = fileInfo.DirectoryName; var pdfPath = Path.Combine(dirName, pdfName); Workbook workbook = new Workbook(); workbook.LoadFromFile(path);<br> workbook.ConverterSetting.SheetFitToWidth = true ; //适应页面宽度,自动转为横版 workbook.SaveToFile(pdfPath, Spire.Xls.FileFormat.PDF); if (isDelOldFile) { System.IO.File.Delete(path); } return pdfPath; } /// <summary> /// 多个pdf文件合并成一个文件 /// </summary> /// <param name="list">pdf文件物理路径</param> /// <param name="filePath">pdf合并后保存的文件名称</param> /// <param name="isDelOldFile">是否删除合并前的pdf文件</param> /// <returns></returns> public static string MergePdf(List< string > list, string filePath, bool isDelOldFile = false ) { try { if (!list.HasItems()) return "" ; if (!list.All(e => e.EndsWith( ".pdf" ) || e.EndsWith( ".PDF" ))) return "只支持pdf文件合并,请检查传入的文件类型!" ; string [] fileNames = list.ToArray(); PdfDocumentBase doc = PdfDocument.MergeFiles(fileNames); doc.Save(filePath); //要删除掉合并前的PDF文档 if (isDelOldFile) { foreach ( var item in list) { if (System.IO.File.Exists(item)) System.IO.File.Delete(item); } } } catch (Exception ex) { throw ex; } return filePath; } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人