gpt4 book ai didi

c# - Open-XML 保存 word 文档产生损坏的文件

转载 作者:行者123 更新时间:2023-11-30 14:15:28 24 4
gpt4 key购买 nike

虽然我是 Open-XML 世界的新手,但我在使用它时已经遇到了一些麻烦/问题。其中大部分很容易解决,但我无法解决这个问题:

public class ReportDocument : IDisposable
{
private MemoryStream stream;
private WordprocessingDocument document;
private MainDocumentPart mainPart;

public byte[] DocumentData
{
get
{
this.document.ChangeDocumentType(WordprocessingDocumentType.MacroEnabledDocument);
byte[] documentData = this.stream.ToArray();
return documentData;
}
}

public ReportDocument()
{
byte[] template = DocumentTemplates.SingleReportTemplate;
this.stream = new MemoryStream();
stream.Write(template, 0, template.Length);
this.document = WordprocessingDocument.Open(stream, true);
this.mainPart = document.MainDocumentPart;
}

public void SetReport(Report report)
{
Body body = mainPart.Document.Body;
var placeholder = body.Descendants<SdtBlock>();
this.SetPlaceholderTextValue(placeholder, "Company", WebApplication.Service.Properties.Settings.Default.CompanyName);
this.SetPlaceholderTextValue(placeholder, "Title", String.Format("Status Report for {0} to {1}", report.StartDate.ToShortDateString(),
report.ReportingInterval.EndDate.ToShortDateString()));
//this.SetPlaceholderTextValue(placeholder, "Subtitle", String.Format("for {0}", report.ReportingInterval.Project.Name));
this.SetPlaceholderTextValue(placeholder, "Author", report.TeamMember.User.Username);
this.SetPlaceholderTextValue(placeholder, "Date", String.Format("for {0}", DateTime.Today.ToShortDateString()));
}

private void SetPlaceholderTextValue(IEnumerable<SdtBlock> sdts, string alias, string value)
{
SdtContentBlock contentBlock = this.GetContentBlock(sdts, alias);
Text text = contentBlock.Descendants<Text>().First();
text.Text = value;
}

private SdtContentBlock GetContentBlock(IEnumerable<SdtBlock> sdts, string alias)
{
return sdts.First(sdt => sdt.Descendants<SdtAlias>().First().Val.Value == alias).SdtContentBlock;
}

public void Dispose()
{
this.document.Close();
}
}

所以我创建了一个新文档,基于它通过内存流获得的模板,并希望在进行更改时将其写回内存流。

最大的问题是,当我保存生成的字节数组时,数据 docx 文件已损坏:

.\word中的document.xml叫做document2.xml.\word_rels 中的 document.xml.rels 称为 document2.xml.rels,它包含我希望你们中的一些人能够为此提供好的解决方案。

MFG清酒寿司大

最佳答案

将您的 DocumentData 属性更改为此,我认为它应该可以工作。重要的是在读取内存流之前关闭文档。

public byte[] DocumentData
{
get
{
this.document.ChangeDocumentType(WordprocessingDocumentType.MacroEnabledDocument);
this.document.MainDocumentPart.Document.Save();
this.document.Close();
byte[] documentData = this.stream.ToArray();
return documentData;
}
}

关于c# - Open-XML 保存 word 文档产生损坏的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10050628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com