Word 2007 将其文档保存为 .docx 格式,这实际上是一个 zip 文件,其中包含大量内容,包括带有文档的 xml 文件。

我希望能够获取 .docx 文件并将其放入我的 asp.net Web 应用程序中的文件夹中,并让代码打开 .docx 文件并将文档(的 xml 部分)呈现为网页。

我一直在网上搜索有关这方面的更多信息,但到目前为止还没有找到太多。我的问题是:

  1. 您会 (a) 使用 XSLT 将 XML 转换为 HTML,或者 (b) 使用 .net 中的 xml 操作库(例如 3.5 中的 XDocument 和 XElement)转换为 HTML 或 (c) 其他?
  2. 您知道有哪些开源库/项目已经做到了这一点,我可以将其用作起点吗?

谢谢!

有帮助吗?

解决方案

尝试这个 邮政?我不知道,但可能就是你正在寻找的。

其他提示

我写 猛犸象.js, ,这是一个将 docx 文件转换为 HTML 的 JavaScript 库。如果你想在 .NET 中进行服务器端渲染,还有一个 .NET 版本的 Mammoth 在 NuGet 上可用.

Mammoth 尝试通过查看语义信息来生成干净的 HTML——例如,在 Word 中映射段落样式(例如 Heading 1)到 HTML/CSS 中适当的标签和样式(例如 <h1>)。如果您想要产生精确视觉副本的东西,那么猛犸象可能不适合您。如果您有一些已经结构良好的内容并希望将其转换为整洁的 HTML,Mammoth 可能会满足您的要求。

Word 2007 有一个可用于转换为 HTML 的 API。这是一篇谈论它的帖子 http://msdn.microsoft.com/en-us/magazine/cc163526.aspx. 。你可以找到有关API的文档,但我记得API中有一个转换为HTML的功能。

此代码将有助于转换 .docx 文件到文本

function read_file_docx($filename){

    $striped_content = '';
    $content = '';

    if(!$filename || !file_exists($filename)) { echo "sucess";}else{ echo "not sucess";}

    $zip = zip_open($filename);

    if (!$zip || is_numeric($zip)) return false;

    while ($zip_entry = zip_read($zip)) {

        if (zip_entry_open($zip, $zip_entry) == FALSE) continue;

        if (zip_entry_name($zip_entry) != "word/document.xml") continue;

        $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

        zip_entry_close($zip_entry);
    }// end while

    zip_close($zip);

    //echo $content;
    //echo "<hr>";
    //file_put_contents('1.xml', $content);     

    $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
    $content = str_replace('</w:r></w:p>', "\r\n", $content);
     //header("Content-Type: plain/text");


    $striped_content = strip_tags($content);


      $striped_content = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t@\/\_\(\)]/","",$striped_content);

    echo nl2br($striped_content); 
}

我正在使用互操作。这有点问题,但在大多数情况下工作得很好。

using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;

这个返回 html 转换文档的路径列表

public List<string> GetHelpDocuments()
    {

        List<string> lstHtmlDocuments = new List<string>();
        foreach (string _sourceFilePath in Directory.GetFiles(""))
        {
            string[] validextentions = { ".doc", ".docx" };
            if (validextentions.Contains(System.IO.Path.GetExtension(_sourceFilePath)))
            {
                sourceFilePath = _sourceFilePath;
                destinationFilePath = _sourceFilePath.Replace(System.IO.Path.GetExtension(_sourceFilePath), ".html");
                if (System.IO.File.Exists(sourceFilePath))
                {
                    //checking if the HTML format of the file already exists. if it does then is it the latest one?
                    if (System.IO.File.Exists(destinationFilePath))
                    {
                        if (System.IO.File.GetCreationTime(destinationFilePath) != System.IO.File.GetCreationTime(sourceFilePath))
                        {
                            System.IO.File.Delete(destinationFilePath);
                            ConvertToHTML();
                        }
                    }
                    else
                    {
                        ConvertToHTML();
                    }

                    lstHtmlDocuments.Add(destinationFilePath);
                }
            }


        }
        return lstHtmlDocuments;
    }

这个是将 doc 转换为 html 的。

private void ConvertToHtml()
    {
        IsError = false;
        if (System.IO.File.Exists(sourceFilePath))
        {
            Microsoft.Office.Interop.Word.Application docApp = null;
            string strExtension = System.IO.Path.GetExtension(sourceFilePath);
            try
            {
                docApp = new Microsoft.Office.Interop.Word.Application();
                docApp.Visible = true;

                docApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                object fileFormat = WdSaveFormat.wdFormatHTML;
                docApp.Application.Visible = true;
                var doc = docApp.Documents.Open(sourceFilePath);
                doc.SaveAs2(destinationFilePath, fileFormat);
            }
            catch
            {
                IsError = true;
            }
            finally
            {
                try
                {
                    docApp.Quit(SaveChanges: false);

                }
                catch { }
                finally
                {
                    Process[] wProcess = Process.GetProcessesByName("WINWORD");
                    foreach (Process p in wProcess)
                    {
                        p.Kill();
                    }
                }
                Marshal.ReleaseComObject(docApp);
                docApp = null;
                GC.Collect();
            }
        }
    }

杀字不好玩,但总不能让它挂在那里挡住别人吧?

在 web/html 中,我将 html 渲染到 iframe 中。

有一个下拉菜单,其中包含帮助文档列表。Value 是 html 版本的路径,text 是文档的名称。

private void BindHelpContents()
    {
        List<string> lstHelpDocuments = new List<string>();
        HelpDocuments hDoc = new HelpDocuments(Server.MapPath("~/HelpDocx/docx/"));
        lstHelpDocuments = hDoc.GetHelpDocuments();
        int index = 1;
        ddlHelpDocuments.Items.Insert(0, new ListItem { Value = "0", Text = "---Select Document---", Selected = true });

        foreach (string strHelpDocument in lstHelpDocuments)
        {
            ddlHelpDocuments.Items.Insert(index, new ListItem { Value = strHelpDocument, Text = strHelpDocument.Split('\\')[strHelpDocument.Split('\\').Length - 1].Replace(".html", "") });
            index++;
        }
        FetchDocuments();

    }

当选定的索引发生变化时,它会被重新渲染为框架

    protected void RenderHelpContents(object sender, EventArgs e)
    {
        try
        {
            if (ddlHelpDocuments.SelectedValue == "0") return;
            string strHtml = ddlHelpDocuments.SelectedValue;
            string newaspxpage = strHtml.Replace(Server.MapPath("~/"), "~/");
            string pageVirtualPath = VirtualPathUtility.ToAbsolute(newaspxpage);// 
            documentholder.Attributes["src"] = pageVirtualPath;
        }
        catch
        {
            lblGError.Text = "Selected document doesn't exist, please refresh the page and try again. If that doesn't help, please contact Support";
        }
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top