Excel转PDF基于Microsoft.Office.Interop.Excel

一.使用背景

我们在项目中使用的过程中很多时候需要转pdf,但是有很多控件不行,或者格式不对,所以很多时候只能使用Office的pdf
代码如下

二.源码

       /// <summary>
        /// Excel转PDF通过路径
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public string ConsultPDF(string filePath, string originName)
        {
            originName = originName.Replace(".xlsx", "");
            if (filePath.IndexOf(":", StringComparison.Ordinal) < 0) { filePath = DirFileHelper.GetMapPath("~/" + filePath); }
            string oldPath = filePath;
            string newPath = DirFileHelper.GetFilePath(filePath) + "\\" + originName + ".pdf";
            string result = "";
            ApplicationClass application = null;
            Workbook workBook = null;

            try
            {
                application = new ApplicationClass();
                workBook = application.Workbooks.Open(oldPath);
                workBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, newPath, XlFixedFormatQuality.xlQualityStandard, true, false);

                result = newPath;
            }
            catch (Exception ex)
            {
                result = "false:" + ex.Message;
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true);
                }
                if (application != null)
                {
                    application.Quit();
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            string serverPath = DirFileHelper.GetMapPath("~/");
            result = result.Replace(@"" + serverPath, "");
            return result;
        }

网上组件配置

打开comexp.msc -32

2、Microsoft Excel Application、和Microsoft Word 97-2003 Document属性里面进行配置,如下:
  标识:设为“交互式用户”
  安全:启动和激活权限添加“NETWORK SERVICE”,勾选本地启动和本地激活,访问权限添加类似

异常解决办法

当我们使用了这个插件之后也在网上使用了组件服务配置,但是发现如果在服务器上使用,有时候会掉线
其实如果要解决,实际上是我们组件服务配置错了在这里插入图片描述
游览选择管理员
在这里插入图片描述
最终输入密码即可
在这里插入图片描述

C#中,如果不安装Office,可以使用开源的第三方库来实现Excel换为PDF,例如使用EPPlus和PdfSharp库。 EPPlus是一个免费的开源库,可以用于读写Excel文件。它可以在不安装Office的情况下读写Excel文件。要将Excel换为PDF,您需要使用EPPlus中的Worksheet对象,将其导出到PDF格式,并使用PdfSharp库将其保存为PDF文件。以下是一个示例代码: ```csharp using OfficeOpenXml; using PdfSharp.Drawing; using PdfSharp.Pdf; public void ConvertExcelToPdf(string excelFilePath, string pdfFilePath) { using (ExcelPackage package = new ExcelPackage(new FileInfo(excelFilePath))) { ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; PdfDocument document = new PdfDocument(); PdfPage page = document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XFont font = new XFont("Verdana", 8); XStringFormat format = new XStringFormat(); int y = 0; foreach (var row in worksheet.Cells.Rows) { int x = 0; foreach (var cell in row) { string value = cell.Value?.ToString() ?? string.Empty; gfx.DrawString(value, font, XBrushes.Black, new XRect(x, y, cell.Style.TextRotation == 0 ? cell.FullWidth : cell.FullHeight, cell.Style.TextRotation == 0 ? cell.FullHeight : cell.FullWidth), format); x += cell.Style.TextRotation == 0 ? cell.FullWidth : cell.FullHeight; } y += row.Height; } document.Save(pdfFilePath); } } ``` 另一个库是PdfSharp,它是一个免费的开源库,可以用于创建和处理PDF文件。您可以使用ExcelDataReader库读取Excel文件中的数据,并将其写入到PdfSharp的PdfDocument对象中。以下是一个示例代码: ```csharp using ExcelDataReader; using PdfSharp.Drawing; using PdfSharp.Pdf; public void ConvertExcelToPdf(string excelFilePath, string pdfFilePath) { using (var stream = File.Open(excelFilePath, FileMode.Open, FileAccess.Read)) { using (var reader = ExcelReaderFactory.CreateReader(stream)) { var document = new PdfDocument(); var page = document.AddPage(); var gfx = XGraphics.FromPdfPage(page); var font = new XFont("Verdana", 8); var format = new XStringFormat(); while (reader.Read()) { var y = reader.Depth * 15; for (int i = 0; i < reader.FieldCount; i++) { var x = i * 100; var value = reader.GetValue(i)?.ToString() ?? string.Empty; gfx.DrawString(value, font, XBrushes.Black, new XRect(x, y, 100, 15), format); } } document.Save(pdfFilePath); } } } ``` 请注意,这些库可能不支持所有的Excel功能,但它们可以满足大多数情况下的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

因为有你更精彩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值