![](/img/trans.png)
[英]Is it possible to insert pieces of RTF text into a Word document (.docx) using OpenXml?
[英]Creating a word document (docx) with OpenXml
首先,我说我已经阅读了其他类似的问题,但是该解决方案(下面复制)对我不起作用。
我正在尝试使用.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>
所以我的解决方案看起来像这样。 我有几个全局变量:
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);
}
}
而且效果很好。 尝试这个。
对于任何其他遇到此问题的人-这是open-xml-sdk中的错误,请在此处报告: https : //github.com/OfficeDev/Open-XML-SDK/issues/249
看起来_rels / .rels隐藏文件中的路径存在问题,并在Mac上加上了额外的反斜杠,从而引起了问题。
我当前的修复方法是使用现有的空文档作为模板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.