ASP.NET在线预览WORD

Posted on   SJ_1986  阅读(708)  评论(0编辑  收藏  举报

在网上找到一个ASP.NET在线预览WORD的文章,觉得蛮实用的,和大家分享一下。原网址:http://hi.baidu.com/zhangguoli2012/item/d6cc4c14cd44778e88a95697

该方法的原理是:将word转换为html,然后在网页上展示html就OK咯!

不过该方法只针对纯文本的WORD有效,若WORD中有页面页脚、图片等信息,则会丢失这些信息。(原作者建议:使用flashpaper将doc转化为flash可以解决丢失信息的问题)

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Word = Microsoft.Office.Interop.Word;
using System.IO;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string path = Server.MapPath("~/temp/新建 Microsoft Word 文档.docx");
        string filename = WordToHtml(path);
        StreamReader fread = new StreamReader(filename, System.Text.Encoding.GetEncoding("gb2312"));
        string ss = fread.ReadToEnd();
        Response.Write(ss);
        fread.Close();
        fread.Dispose();
    }

    /// <summary>
    /// word转成html
    /// </summary>
    /// <param name="wordFileName"></param>

    private string WordToHtml(object wordFileName)
    {
        //在此处放置用户代码以初始化页面
        Word.ApplicationClass word = new Word.ApplicationClass();
        Type wordType = word.GetType();
        Word.Documents docs = word.Documents;


        //打开文件
        Type docsType = docs.GetType();
        Word.Document doc = (Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFileName, true, true });
        //转换格式,另存为
        Type docType = doc.GetType();
        string wordSaveFileName = wordFileName.ToString();
        string strSaveFileName = wordSaveFileName.Substring(0, wordSaveFileName.Length - 3) + "html";
        object saveFileName = (object)strSaveFileName;
        docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML });
        docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);

        //退出 Word
        wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
        return saveFileName.ToString();
    }

}

随笔 - 11, 文章 - 0, 评论 - 1, 阅读 - 99043

Copyright © 2025 SJ_1986
Powered by .NET 9.0 on Kubernetes

点击右上角即可分享
微信分享提示