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”,勾选本地启动和本地激活,访问权限添加类似

异常解决办法

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

橙子主题打折出售

其实我不卖,主要是这里是放广告的,所以就放了一个
毕竟主题都没做完,卖了也是坑.

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

热门文章

WordPress 后台编辑器样式实现直接预览 在WordPress3.0以后,有一个新的实用功能:你可以更改默认后台编辑器(TinyMCE)的样...WordPress后台编辑器样式实现直接预览 作者:Pastore Antonio
1533 浏览量
【干货】Chrome插件(扩展)开发全攻略 写在前面我花了将近一个多月的时间断断续续写下这篇博文,并精心写下完整demo,写博客的辛苦大家懂的...【干货】Chrome插件(扩展)开发全攻略 作者:Pastore Antonio
1488 浏览量
memcached 处理 多端口:https://blog.csdn.net/Erica_1230/article/deta...memcached处理 作者:Pastore Antonio
1481 浏览量
使用Nginx+WordPress搭建个人网站 背景很多研究技术的朋友喜欢写博客。如果希望搭建一个完全属于自己的网站,也并不困难。这里简要分享一下...使用Nginx+WordPress搭建个人网站 作者:Pastore Antonio
1453 浏览量
C#图片处理 通常对一幅图片的处理包括:格式变换,缩放(Scale),翻转(Rotate),截取(Clip),滤镜...C#图片处理 作者:Pastore Antonio
1445 浏览量