c# - 使用 OpenXML 和 MemoryStream 在 ASP.NET 程序中编辑和保存 .docx

标签 c# asp.net openxml memorystream

我正在编写一个项目,允许您直接从站点编辑 .docx 文档(我有一个需要编辑的模板)并将它们保存到您的计算机。 我在保存已在文件中编辑的所有信息时遇到问题。

using (MemoryStream memoryStream = new MemoryStream())
{
    memoryStream.Write(byteArray, 0, byteArray.Length);
    using (WordprocessingDocument wDoc = WordprocessingDocument.Open(memoryStream, true))
    {
        string docText = null;
        using (StreamReader sr = new StreamReader(wDoc.MainDocumentPart.GetStream()))
        {
            docText = sr.ReadToEnd();
        }

        var senderData = Sender_Textbox.Text;
        var receiverData = Receiver_Textbox.Text;
        var subjectData = Subject_Textbox.Text;
        var contentData = Content_Textbox.Text;

        docText = ReplaceData(docText, "receiver", receiverData);
        docText = ReplaceData(docText, "sender", senderData);
        docText = ReplaceData(docText, "subject", subjectData);
        docText = ReplaceData(docText, "content", contentData);

        using (StreamWriter sw = new StreamWriter(wDoc.MainDocumentPart.GetStream(FileMode.Create)))
        {
            sw.Write(docText);
        }
    }
    Session["ByteArray"] = memoryStream.ToArray();
}

static string ReplaceData(string docText, string oldText, string newText)
{
    var regexText = new Regex(oldText);
    return regexText.Replace(docText, newText);
}

我用了this来自 Office Dev Center 的教程,它在离线解决方案中运行良好。 StreamWriter 部分不起作用,我下载了一个完全没有变化的文档。如何保存我在 wDoc 中在线编辑的所有信息?

最佳答案

您正在将更新后的文档文本写入 StreamWriter sw 但随后未对它执行任何操作。然后,您将 session 变量设置为原始的、未经编辑的字节数组 memoryStream(这可能是您返回没有任何更改的文档的原因)。

您需要将 sw 转换为字节数组并将其放入 Session["ByteArray"] 中。

此外, session 变量中的大字节数组似乎不是一个非常好的主意。

关于c# - 使用 OpenXML 和 MemoryStream 在 ASP.NET 程序中编辑和保存 .docx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36921101/

相关文章:

c# - 在 C# 中创建常量字典

javascript - Javascript 的相对 URL

.net - 将图表添加到 WordprocessingML

c# - 从 Active Directory 中检索包含电子邮件地址的 C# 列表

c# - 使用经度和纬度查找最近的位置

c# - 何时在并发中使用锁语句

asp.net - 不指定控件 ID 的优点?

c# - 如何创建使用表格作为数据源的折线图?

openxml - AbstractNum 和 NumberingInstance 的用途

c# - 如何使用隐式实现在 VB.NET 中创建接口(interface)