使用OpenXml创建Word文档(.docx)

3
让我先说一下,我已经看过其他类似的问题,但解决方案(如下所示)对我不起作用。
我正在尝试使用.NET Core和OpenXML(使用DocumentFormat.OpenXml 2.7.2 nuget包)创建一个Word文档(docx)。 看起来很简单,但是它总是出现问题。当我尝试打开文档时,会出现文件损坏、截断或格式不正确的错误。
这是我的代码(我在许多教程中找到它):
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.IO;

public Stream GetDocument()
        {
            var stream = new MemoryStream();

            using (WordprocessingDocument doc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
            {
                MainDocumentPart mainPart = doc.AddMainDocumentPart();

                new Document(new Body()).Save(mainPart);

                Body body = mainPart.Document.Body;
                body.Append(new Paragraph(
                            new Run(
                                new Text("Hello World!"))));

                mainPart.Document.Save();

            }
            stream.Seek(0, SeekOrigin.Begin);

            return stream;

        }

将其保存为以下格式:
 public static void Test()
        {
            DocxWriter writer = new DocxWriter();

            string filepath = Directory.GetCurrentDirectory() + @"/test.docx";

            var stream = writer.GetDocument();

            using (var fileStream = new FileStream(filepath, FileMode.Create, FileAccess.Write))
            {
                stream.CopyTo(fileStream);
            }

            stream.Dispose();
        }

编辑:提取docx后,我可以找到一个底层的xml,看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
    <w:body>
        <w:p>
            <w:r>
                <w:t>Hello World!</w:t>
            </w:r>
        </w:p>
    </w:body>
</w:document>

你使用的是哪个版本的Office打开.docx文件? - Niladri
@Niladri 实际上,我是在 Mac 上打开它的,没有使用 Office,但我打开其他 docx 文件没有问题。我已经让其他人尝试在 Windows 上打开它,结果显示类似的问题。这就是为什么我认为这不是阅读器的问题。 - daneejela
我刚刚验证了这个可以正常工作。在Win10上构建、运行并生成文件,文件可以在Word2016中打开。你能否发布更多关于你的项目的细节,因为到目前为止,所有的都正常工作。 - Taterhead
我也将文件通过电子邮件发送到我的 Mac,它在 Word for Mac 上打开了。 - Taterhead
2个回答

2
对于任何遇到此问题的人 - 这是 open-xml-sdk 中的一个错误,报告在这里:https://github.com/OfficeDev/Open-XML-SDK/issues/249 看起来 _rels/.rels 隐藏文件中的路径存在问题,在 Mac 上会导致额外的反斜杠引起问题。
我的当前修复方法/黑客是使用现有的空文档作为模板。

2

我的解决方案如下。我有几个全局变量:

private MemoryStream _Ms;
private WordprocessingDocument _Wpd;

那么创建方法看起来像这样:

public Doc()
{
    _Ms = new MemoryStream();
    _Wpd = WordprocessingDocument.Create(_Ms, WordprocessingDocumentType.Document, true);
    _Wpd.AddMainDocumentPart();
    _Wpd.MainDocumentPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
    _Wpd.MainDocumentPart.Document.Body = new Body();
    _Wpd.MainDocumentPart.Document.Save();
    _Wpd.Package.Flush();
}

保存方法如下:

public void SaveToFile(string fullFileName)
{
    _Wpd.MainDocumentPart.Document.Save();

    _Wpd.Package.Flush();

    _Ms.Position = 0;
    var buf = new byte[_Ms.Length];
    _Ms.Read(buf, 0, buf.Length);

    using (FileStream fs = new System.IO.FileStream(fullFileName, System.IO.FileMode.Create))
    {
        fs.Write(buf, 0, buf.Length);
    }
}

它工作得很好。试试这个。


谢谢,但是当我尝试打开它时,它仍然给我相同的错误 :( - daneejela
非常抱歉回复晚了。我已经点赞你的回答,因为你付出了努力,但它对我仍然没有用。我猜测这是跨平台部分存在一些问题。我已经注意到其他几位作者(例如onedrive.live.com,http://evidenceprime.github.io/html-docx-js/test/sample.html等)也有这种行为。他们都生成无法在Mac上使用的docx文件。更奇怪的是,我可以在Mac上打开的docx,在Windows上却无法打开。 - daneejela

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接