1
我的代碼如下。我試圖用Open XML打開Word文檔並更改某些文本。然後必須將文件發送給客戶,以便將其保存在PC上或打開。它向客戶發送文件,但它是空白的。當我保存我的InMemory文檔時,它說文件不能打開,它必須至少包含一個根元素。我正在使用Visual STudio 2010 Express。請幫幫我。我的代碼有什麼問題?asp.net openxml打開docx,更改內容和流到用戶
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()
myDocument.MainDocumentPart.FeedData(ms)似乎關閉了ms存儲器流。如果我刪除所有mems內存流並將其替換爲我的第一個內存流,它會給我以下消息:無法訪問關閉的流。 – henrysh
我不明白你爲什麼用ms替換mem?爲什麼是mem,即使你沒有做任何事情。 –