3

虽然我是 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清酒寿司大

4

1 回答 1

7

将您的 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;
        }
    }
于 2012-10-02T11:01:11.357 回答