1
我創建了一個需要Word模板的DLL,我有使用openXML編輯文檔的代碼,然後通過內存流將結果發送到將文檔下載到用戶的Web服務。問題是內存流發送是沒有更新的原始模板文檔,或者發送文檔明顯損壞的更新的Word文檔XML格式。下面是代碼:使用openxml編輯docx會返回無效的內存流
string strTemplate = AppDomain.CurrentDomain.BaseDirectory + "Report Template.docx";
WordprocessingDocument wdDocument;
//stream the template
byte[] fileBytes = File.ReadAllBytes(strTemplate);
MemoryStream memstreamDocument = new MemoryStream();
memstreamDocument.Write(fileBytes, 0, (int)fileBytes.Length);
wdDocument = WordprocessingDocument.Open(memstreamDocument, true);
//CODE TO UPDATE TEMPLATE
//Save entire document
wdDocument.MainDocumentPart.Document.Save();
保存文件,如果使用下面的代碼的內存流返回沒有任何文檔更新原始模板後:
return memstreamDocument;
如果使用下面的代碼存儲流與更新返回OpenXML的數據,但該文件已損壞:
MemoryStream memstreamUpdatedDocument = new MemoryStream();
Stream streamDocument = wdDocument.MainDocumentPart.GetStream();
streamDocument.CopyTo(memstreamUpdatedDocument);
return memstreamUpdatedDocument;
這是我在網絡服務的正常工作代碼:
HttpResponse response = HttpContext.Current.Response;
MemoryStream stream = GR.GetReport("", intReportID, Culture, ConnectionString, false);
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.AddHeader("content-disposition", "attachment; filename=\"" + "Report_" + intReportID+ ".docx\"");
response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
stream.Position = 0;
stream.CopyTo(response.OutputStream);
response.End();
return response;