首先我要说的是,我已经阅读过其他类似的问题,但解决方案(复制如下)对我来说不起作用。
我正在尝试使用.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>
所以我的解决方案看起来像这样。我的全局变量很少:
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(); // _Wpd.Dispose();
}
保存方法如下所示:
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);
}
}
而且效果很好。试试这个。
对于遇到此问题的其他人 - 这是 open-xml-sdk 中的一个错误,报告如下: https://github.com/OfficeDev/Open-XML-SDK/issues/249
看起来 _rels/.rels 隐藏文件的路径存在问题,添加了额外的反斜杠,导致 Mac 上出现问题。
我当前的修复/破解是使用现有的空文档作为模板。