【发布时间】:2017-09-05 06:50:03
【问题描述】:
首先让我说我已经阅读了其他类似的问题,但解决方案(复制如下)对我不起作用。
我正在尝试使用 .net 核心和 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 实际上,我是在没有办公室的情况下从 Mac 打开它,但打开其他 docx 文件没有问题。我已经要求其他人尝试在 Windows 上打开它,它显示出类似的问题。这就是为什么我认为这不是读者的问题。
-
我刚刚验证了它可以正常工作。在 Win10 上构建、运行和生成文件。并在 Word2016 中打开文件。您能否发布有关您的项目的更多详细信息,因为到目前为止所有这些都运行良好。
-
我还将文件通过电子邮件发送到我的 mac,并在 Word for mac 上打开。
标签: c# .net-core openxml docx openxml-sdk