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