返回openxml文档的字节数组

时间:2016-07-12 13:29:13

标签: c# .net openxml

我使用以下代码生成openxml文档并将其保存在服务器上并且工作正常,但是现在我尝试将其生成为字节流,以便立即投放而不保存到服务器但文档在此过程中被破坏。

工作代码

 public static void CreateWordDoc(List<objReplace> lstReplace, String TemplateFile, String OutputPath)
        {
            File.Delete(OutputPath);
            File.Copy(TemplateFile, OutputPath);

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(OutputPath, true))
            {  
                string docText = null;

                using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                    docText = sr.ReadToEnd();

                foreach (var ro in lstReplace)
                {
                    Regex regexText = new Regex(ro.Find);
                    docText = regexText.Replace(docText, ro.Replace);
                }

                using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
                {
                    sw.Write(docText);
                }
            }
        }

产生损坏的XML的代码 - 我想要工作

 public static byte[] CreateWordDocToStream(List<objReplace> lstReplace, String TemplateFile)
        {
            string docText = null;
            byte[] filebytes = File.ReadAllBytes(TemplateFile);
            using (MemoryStream stream = new MemoryStream(filebytes))
            {
                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
                {
                    using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                        docText = sr.ReadToEnd();

                    foreach (var ro in lstReplace)
                    {
                        Regex regexText = new Regex(ro.Find);
                        docText = regexText.Replace(docText, ro.Replace);
                    }
                }
            }

            return Encoding.ASCII.GetBytes(docText);
        }

0 个答案:

没有答案