需要nuget 安装FreeSpire.XLS Free为免费版不会带水印
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);
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;
}
}
}