[英]Convert open xml string to byte[]
所以,我正在使用OpenXML編輯word文檔。 由於某些原因,我將它全部轉換為string
:
//conversion du byte en memorystream
using (var file = new MemoryStream(text))
using (var reader = new StreamReader(file))
{
WordprocessingDocument wordDoc = WordprocessingDocument.Open(file, true);
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
}
然后,我將其轉換為字節。
但是,簡單的轉換不起作用:
byte[] back2Byte = System.Text.Encoding.ASCII.GetBytes(docText );
因為字符串是一個打開的xml字符串。
試過這個,但是當我嘗試用Word打開它時,總是有一個損壞的文件:
var repo = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(docText));
byte[] buffer = new byte[16 * 1024];
MemoryStream ms = new MemoryStream();
int read;
while ((read = repo.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
byte[] back2Byte = ms.ToArray();
所以,這也不起作用:
byte[] back2Byte = new byte[docText.Length * sizeof(char)];
System.Buffer.BlockCopy(docText.ToCharArray(), 0, back2Byte, 0, back2Byte.Length);
編輯:經過一些檢查,它似乎是作為openxml文檔寫入數據庫,因此,word無法讀取它。 用記事本打開它時沒有錯誤
我怎么能糾正這個?
所以,真正的問題是,如何將OpenXML字符串轉換為可以在word中打開的字節?
你不能做這種事情。 您只獲取OpenXML文檔的一部分的字節。 根據定義,所有Microsoft Office文檔都是多部分OpenXML文檔。 理論上,您可以使用當前使用的技術捕獲所有部件的字節,但您還必須捕獲重建多部件文檔所需的所有部件/關系信息。 你最好只讀取文件的所有字節並按原樣存儲它們:
// to read the file as bytes
var fileName = @"C:\path\to\the\file.xlsx";
var fileBytes = File.ReadAllBytes(fileName);
// to recreate the file from the bytes
File.WriteAllBytes(fileName, fileBytes)
如果您需要這些字節的字符串形式,請嘗試以下方法:
// to convert bytes to a (non-readable) text form
var fileContent = Convert.ToBase64String(fileBytes);
// to convert base-64 back to bytes
var fileBytes = Convert.FromBase64String(fileContent);
無論哪種方式,都絕對不需要將OpenXML SDK用於您的用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.