OpenXml在Word中保存Excel嵌入对象c#

时间:2013-05-07 08:31:05

标签: c# excel ms-word openxml

我正在尝试打开一个excel表,它嵌入word文档中。 因为它存储在二进制数据中,所以我从流中读取并获取它。在excel表和word文档中有一些值,如$ amount,我替换它们,但是当我尝试保存嵌入对象时,更改不会保存,而word文档中的更改是。哪里出错了?这让我发疯了。

这是我的代码

PaymentData data = PaymentData.FromString(args[1]);
Dictionary<string, string> replaceDic = new Dictionary<string, string>()
{
    { "$value", data.Somedata }
};
string template = Path.GetFullPath("resources/rdoc.docx");
string documentText;

byte[] byteArray = File.ReadAllBytes(template);
using (MemoryStream stream = new MemoryStream())
{
    stream.Write(byteArray, 0, (int)byteArray.Length);
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
    {
        Stream xlStream = wordDoc.MainDocumentPart.EmbeddedPackageParts.First().GetStream();
        ProcessTemplate(xlStream, replaceDic);

        // Reset stream to beginning
        xlStream.Seek(0L, SeekOrigin.Begin);

        wordDoc.MainDocumentPart.EmbeddedPackageParts.First().FeedData(xlStream);

        using (StreamReader reader = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
        {
            documentText = reader.ReadToEnd();
        }


        foreach (KeyValuePair<string, string> pair in replaceDic)
        {
            if (documentText.Contains(pair.Key))
                documentText = documentText.Replace(pair.Key, pair.Value);
        }

        using (StreamWriter writer = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
        {
             writer.Write(documentText);
        }
  }
  // Save the file with the new name
  File.WriteAllBytes("resources/rdoc1.docx", stream.ToArray());
}

private static void ProcessTemplate(Stream template, Dictionary<string, string> replaceDic)
{
      using (var workbook = SpreadsheetDocument.Open(template, true, new OpenSettings() { AutoSave = true }))
      {
          // Replace shared strings
          SharedStringTablePart sharedStringsPart = workbook.WorkbookPart.SharedStringTablePart;
          IEnumerable<x.Text> sharedStringTextElements = sharedStringsPart.SharedStringTable.Descendants<x.Text>();
          DoReplace(sharedStringTextElements, replaceDic);
          // Replace inline strings
          IEnumerable<WorksheetPart> worksheetParts = workbook.WorkbookPart.GetPartsOfType<WorksheetPart>();
          foreach (var worksheet in worksheetParts)
          {
                var allTextElements = worksheet.Worksheet.Descendants<x.Text>();
                DoReplace(allTextElements, replaceDic);
          }

      } // AutoSave enabled
}

private static void DoReplace(IEnumerable<x.Text> textElements, Dictionary<string, string> replaceDic)
{
       foreach (var text in textElements)
       {
            foreach (KeyValuePair<string, string> pair in replaceDic)
            {
                if (text.Text.Contains(pair.Key))
                    text.Text = text.Text.Replace(pair.Key, pair.Value);
            }
       }
}

1 个答案:

答案 0 :(得分:1)

注释掉这一行:

//wordDoc.MainDocumentPart.EmbeddedPackageParts.First().FeedData(xlStream);

ProcessTemplate()函数已经保存了Open XML Excel流内容。