2016-08-24 61 views
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; 

回答

2

審查我提供了一個修改後的代碼片段,應該適合你的OpenXML的使用WordprocessingDocument類從一個文件模板返回修改MemoryStream的需求所提供的代碼之後。您提供的網絡服務代碼片段應按原樣運行。

// file path of template 
string strTemplate = AppDomain.CurrentDomain.BaseDirectory + "Report Template.docx"; 

// create FileStream to read from template 
FileStream fsTemplate = new FileStream(strTemplate, FileMode.Open, FileAccess.Read); 

// create MemoryStream to copy template into and modify as needed 
MemoryStream msDocument = new MemoryStream(); 

// copy template FileStream into document MemoryStream 
fsTemplate.CopyTo(msDocument); 

// close the template FileStream as it is no longer necessary 
fsTemplate.Close(); 

// reset cursor position of document MemoryStream back to top 
// before modifying 
msDocument.Position = 0; 

// create WordProcessingDocument using the document MemoryStream 
using (WordprocessingDocument wdDocument = WordprocessingDocument.Open(msDocument, true)) { 

    //Access the main Workbook part, which contains all references. 
    MainDocumentPart mainPart = wdDocument.MainDocumentPart; 

    /* ... CODE TO UPDATE TEMPLATE ... */ 

    // save modification to main document part 
    wdDocument.MainDocumentPart.Document.Save(); 

    // close wdDocument as it is no longer needed 
    wdDocument.Close(); 
} 

// reset cursor position of document MemoryStream back to top 
msDocument.Position = 0; 

// return memory stream as promised 
return msDocument;