Logo

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

photo

2024年04月09日

一.使用背景

我们在项目中使用的过程中很多时候需要转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”,勾选本地启动和本地激活,访问权限添加类似

异常解决办法

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

本文为原创文章,请注意保留出处!

热门文章

修复群晖Synology Drive client右键菜单缺失问题 本教程主要解决windows10右键菜单中没有SynologyDrive菜单的问题,整体思路是找到...修复群晖SynologyDriveclient右键菜单缺失问题 作者:Pastore Antonio
1826 浏览量
docker如何查看一个镜像内部的目录结构及其内部都有哪些文件 前言:有时候我们会在docker上下载一个镜像,或者是上传一个镜像到docker上,甚至有时候就是在...docker如何查看一个镜像内部的目录结构及其内部都有哪些文件 作者:Pastore Antonio
1808 浏览量
Adobe Acrobat Pro 激活 这里记录了一些AdobeAcrobat的激活教程和组件。浏览量:1,688 作者:Pastore Antonio
1535 浏览量
configure: error: Package requirements (oniguruma) were not met configure:error:Packagerequirements(oniguruma)...configure:error:Packagerequirements(oniguruma)werenotmet 作者:Pastore Antonio
1535 浏览量
追寻日出,找回自己 为什么我要去追寻日出?其实我是一个很懒的人,每次都起不来,直到有一次我在租房中睡到了大天亮,阳光照...追寻日出,找回自己 作者:Pastore Antonio
1515 浏览量