Open-XML保存word文档会生成损坏的文件

时间:2012-04-07 00:18:51

标签: c# ms-word ms-office openxml

虽然我是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 SakeSushiBig

1 个答案:

答案 0 :(得分: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;
        }
    }