【问题标题】:asp.net openxml open docx, change content and stream to userasp.net openxml 打开 docx,更改内容并流式传输给用户
【发布时间】:2012-09-03 19:33:19
【问题描述】:

我的代码如下。我正在尝试使用 Open XML 打开 Word 文档并更改某些文本。然后必须将文档发送给客户,他们可以将其保存在他们的 PC 上或打开它。它将文档发送给客户端,但它是空白的。当我保存我的 InMemory 文档时,它说该文件无法打开,它必须包含至少一个根元素。我正在使用 Visual STudio 2010 Express。请帮我。我的代码有什么问题?

   Dim fileName As String = "directory on server\doc.docx"

    Dim myDocument As WordprocessingDocument = WordprocessingDocument.Open(fileName, True)

    Dim docText As String = Nothing

    Dim sr As StreamReader = New StreamReader(myDocument.MainDocumentPart.GetStream)
    docText = sr.ReadToEnd
    sr.Close()

    Dim regexText As Regex = New Regex("XXXCourtXXX")
    docText = regexText.Replace(docText, "JOHANNESBURG")

    Dim ms As New MemoryStream()
    Dim sw As StreamWriter = New StreamWriter(ms)

    sw.Write(docText)
    myDocument.MainDocumentPart.FeedData(ms)

    Dim mem = New MemoryStream()
    myDocument.MainDocumentPart.GetStream().CopyTo(Response.OutputStream)
    Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    Response.AppendHeader("Content-Disposition", "attachment;filename=Notice.docx")
    mem.Position = 0
    mem.CopyTo(Response.OutputStream)
    Response.Flush()
    Response.End()

【问题讨论】:

    标签: asp.net ms-word openxml


    【解决方案1】:

    您正在调暗一个新的内存流 mem,不向其中写入任何内容,然后将其复制到输出流。删除所有引用你的 mem 变量的行。

    【讨论】:

    • myDocument.MainDocumentPart.FeedData(ms) 似乎关闭了 ms 内存流。如果我删除所有 mems 内存流并将其替换为我的第一个内存流,它会给我以下消息:无法访问已关闭的流。
    • 我不明白你为什么用ms替换mem?为什么 mem 即使在那里你什么也没做。
    猜你喜欢
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 2010-11-12
    • 2015-06-13
    相关资源
    最近更新 更多