用浏览器做在线Office文件可以调用微软Office的接口把Word和Excel转换成html再展示。也能基于WPS吧Word和Excel转换成PDF做在线预览。

基于Office做文件转换,服务器需要装引用的Office软件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Office.Interop.Excel;

namespace LIS.Office14
{
    /// <summary>
    /// Excel预览
    /// </summary>
    public class ExcelPreview
    {
        public static bool Priview(System.Web.UI.Page p, string inFilePath, string outDirPath = "")
        {
            try
            {
                Microsoft.Office.Interop.Excel.Application excel = null;
                Microsoft.Office.Interop.Excel.Workbook xls = null;
                excel = new Microsoft.Office.Interop.Excel.Application();
                object missing = Type.Missing;
                object trueObject = true;
                excel.Visible = false;
                excel.DisplayAlerts = false;
                FileInfo inFileInfo = new FileInfo(inFilePath);
                string randomName = inFileInfo.Name.Replace(inFileInfo.Extension, "");
                xls = excel.Workbooks.Open(inFilePath, missing, trueObject, missing,
                                            missing, missing, missing, missing, missing, missing, missing, missing,
                                            missing, missing, missing);

                //保存Excel为html
                object format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
                //当前工作簿
                Workbook wsCurrent = xls;
                String outputFile = outDirPath + randomName + ".htm";
                wsCurrent.SaveAs(outputFile, format, missing, missing, missing,
                                  missing, XlSaveAsAccessMode.xlNoChange, missing,
                                  missing, missing, missing, missing);
                wsCurrent.Close();
                excel.Quit();
                #region 删除文件
                foreach (string fp in Directory.GetFiles(outDirPath))
                {
                    FileInfo fi = new FileInfo(fp);
                    //超过3000分钟的删除
                    if ((DateTime.Now - fi.CreationTime).Minutes > 3000)
                    {
                        File.Delete(fp);
                        string directoryPath1 = fp.Replace(".htm", ".files");
                        if (Directory.Exists(directoryPath1))
                        {
                            foreach (string fp1 in Directory.GetFiles(directoryPath1))
                            {
                                File.Delete(fp1);
                            }
                            Directory.Delete(directoryPath1);
                        }
                    }
                }
                #endregion
                //重定向生成的html
                p.Response.Redirect("../tmp/" + randomName + ".htm");
            }
            catch (Exception ex)
            {
                p.Response.Write("14异常" + ex.Message);
                return false;
            }
            return true;
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;
using System.IO;

namespace LIS.Office14
{
    /// <summary>
    /// 预览Word
    /// </summary>
    public class WordPreview
    {
        public static bool Priview(System.Web.UI.Page p, string inFilePath, bool isToPdf, string outDirPath = "")
        {
            try
            {
                object missingType = Type.Missing;
                object readOnly = true;
                object isVisible = false;
                object documentFormat = 8;
                FileInfo inFileInfo = new FileInfo(inFilePath);
                string randomName = inFileInfo.Name.Replace(inFileInfo.Extension, "");
                object htmlFilePath = outDirPath + randomName + ".htm";
                string directoryPath = outDirPath + randomName + ".files";
                if (isToPdf == true)
                {
                    string pdfPath = outDirPath + randomName + ".pdf";
                    bool pdfRet = WordToPDF(inFilePath, pdfPath);
                    if (pdfRet == true)
                    {
                        //重定向打开生成的html
                        p.Response.Redirect("../tmp/" + randomName + ".pdf", false);
                        return true;
                    }
                }
                object filePath = inFilePath;
                //后台打开文档
                Microsoft.Office.Interop.Word.ApplicationClass applicationclass = new Microsoft.Office.Interop.Word.ApplicationClass();
                applicationclass.Documents.Open(ref filePath,
                                                ref readOnly,
                                                ref missingType, ref missingType, ref missingType,
                                                ref missingType, ref missingType, ref  missingType,
                                                ref missingType, ref missingType, ref isVisible,
                                                ref missingType, ref missingType, ref missingType,
                                                ref missingType, ref missingType);
                applicationclass.Visible = false;
                Document document = applicationclass.ActiveDocument;

                //保存文档为html
                document.SaveAs(ref htmlFilePath, ref documentFormat, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType, ref missingType, ref missingType,
                                ref missingType);

                //关闭文档
                document.Close(ref missingType, ref missingType, ref missingType);
                applicationclass.Quit();
                foreach (System.Diagnostics.Process pro in System.Diagnostics.Process.GetProcessesByName("WINWORD"))
                {
                    pro.Kill();
                }
                #region 删除文件
                foreach (string fp in Directory.GetFiles(outDirPath))
                {
                    FileInfo fi = new FileInfo(fp);
                    //超过3000分钟的删除
                    if ((DateTime.Now - fi.CreationTime).Minutes > 3000)
                    {
                        File.Delete(fp);
                        string directoryPath1 = fp.Replace(".htm", ".files");
                        if (Directory.Exists(directoryPath1))
                        {
                            foreach (string fp1 in Directory.GetFiles(directoryPath1))
                            {
                                File.Delete(fp1);
                            }
                            Directory.Delete(directoryPath1);
                        }
                        
                    }
                }
                #endregion
                //重定向打开生成的html
                p.Response.Redirect("../tmp/" + randomName + ".htm", false);
            }
            catch (Exception ex)
            {
                p.Response.Write("14异常" + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 把word转PDF再展示
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        public static bool WordToPDF(string sourcePath, string targetPath)
        {
            bool result = false;
            Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
            Document document = null;
            try
            {
                application.Visible = false;
                document = application.Documents.Open(sourcePath);
                document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF);
                result = true;
            }
            catch (Exception e)
            {
                result = false;
            }
            finally
            {
                document.Close();
                application.Quit();
                foreach (System.Diagnostics.Process pro in System.Diagnostics.Process.GetProcessesByName("WINWORD"))
                {
                    pro.Kill();
                }
            }
            return result;
        }
    }
    
}

基于WPS做转换,服务器需要装WPS软件。

需要在工程右键添加引用里选Com栏目引用Com主键里的

wps在线预览对接 java_Office

代码部分

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word;
using Excel;

namespace LIS.WPS
{
    /// <summary>
    /// wps转PDF
    /// </summary>
    public static class WpsToPdf
    {
        /// <summary>
        /// word转pdf
        /// </summary>
        /// <param name="source">源<see cref="string"/>.</param>
        /// <param name="newFilePath">新文件路径<see cref="string"/>.</param>
        /// <returns>The <see cref="bool"/>.</returns>
        public static bool WordWpsToPdf(string source, string newFilePath)
        {
            var type = Type.GetTypeFromProgID("KWps.Application");
            dynamic wps = Activator.CreateInstance(type);
            try
            {
                //用wps打开word不显示界面
                dynamic doc = wps.Documents.Open(source, Visible: false);

                //转pdf
                doc.ExportAsFixedFormat(newFilePath, WdExportFormat.wdExportFormatPDF);

                //设置隐藏菜单栏和工具栏
                //wps.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar);
                doc.Close();
            }
            catch (Exception e)
            {
                //添加你的日志代码
                return false;
            }
            finally
            {
                wps.Quit();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            return true;
        }

        /// <summary>
        /// excel转pdf
        /// </summary>
        /// <param name="source">源<see cref="string"/>.</param>
        /// <param name="newFilePath">新文件路径<see cref="string"/>.</param>
        /// <returns>The <see cref="bool"/>.</returns>
        public static bool ExcelToPdf(string source, string newFilePath)
        {
            var type = Type.GetTypeFromProgID("KET.Application");
            dynamic wps = Activator.CreateInstance(type);
            try
            {
                var targetType = XlFixedFormatType.xlTypePDF;
                var missing = Type.Missing;
                //转pdf
                var doc = wps.Application.Workbooks.Open(source, missing, missing, missing, missing, missing,
                    missing, missing, missing, missing, missing, missing, missing, missing, missing);
                doc.ExportAsFixedFormat(targetType, newFilePath, XlFixedFormatQuality.xlQualityStandard, true, false,
                    missing, missing, missing, missing);
                doc.Close();
            }
            catch (Exception e)
            {
                //添加你的日志代码
                return false;
            }
            finally
            {
                wps.Quit();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return true;
        }
    }
}

正常以上做完了在VS模式上基于浏览器做展示就没问题了。但是部署到IIS程序就没有权限访问Com组件。

报下图错误,或者“无权访问Com主键”之类的

wps在线预览对接 java_Interop_02

wps在线预览对接 java_.net_03


这是因为IIS使用的用户和VS调试时候的用户权限不同导致的。我以前按网上很多方法试了,有到Com组件设置权限的,都很麻烦,大部分不好使。以前基于Office做转换试出一个好使的配置:

2.1:在服务器上安装office的Excel软件.

2:在"开始"->"运行"中输入dcomcnfg.exe启动"组件服务"或者dcomcnfg.exe -32

或者comexp.msc -32

wps在线预览对接 java_wps在线预览对接 java_04

3:依次双击"组件服务"->“计算机”->“我的电脑”->“DCOM配置”

4:在"DCOM配置"中找到"Microsoft Excel 应用程序",在它上面点击右键,然后点击"属性",弹出"Microsoft Excel 应用程序属性"对话框

wps在线预览对接 java_.net_05

5:点击"标识"标签,选择"交互式用户"

wps在线预览对接 java_Office_06

6:点击"安全"标签,在"启动和激活权限"上点击"自定义",然后点击对应的"编辑"按钮,在弹出的"安全性"对话框中填加Everyone和IIS_IUSRS用户,分配全部权限

wps在线预览对接 java_Office_07

7:点击"常规"标签,在"身份验证级别"上选择"无"

wps在线预览对接 java_.net_08


Excel同样配置

做WSP对接时候可以按下面配置解决(Office的没试过,应该也好使):

1.右键程序池-》高级设置

wps在线预览对接 java_wps在线预览对接 java_09

2.找到进程权限-》标识

wps在线预览对接 java_wps在线预览对接 java_10


3.选择自定义账户里使用超级管理员用户

wps在线预览对接 java_wps在线预览对接 java_11


wps在线预览对接 java_System_12


希望对做到这块的有帮助,这方面资料比较少,特别涉及到IIS部署不好使的部分。