[英]OpenXml Dotx to Docx Word Found Unreadable Content
我正在嘗試編寫代碼來填充模板的內容控件,然后將其保存為新文件。
我發現這個非常有用的條目Word OpenXml Word 找到了不可讀的內容並在那里使用了代碼。
我從該帖子中復制了代碼,如下所示
public static MemoryStream ReadAllBytesToMemoryStream(string path)
{
byte[] buffer = File.ReadAllBytes(path);
var destStream = new MemoryStream(buffer.Length);
destStream.Write(buffer, 0, buffer.Length);
destStream.Seek(0, SeekOrigin.Begin);
return destStream;
}
public static void Generate()
{
using MemoryStream stream = ReadAllBytesToMemoryStream(@"c:\Templates\TemplateTest.dotx");
using (WordprocessingDocument wpd = WordprocessingDocument.Open(stream, true))
{
wpd.ChangeDocumentType(WordprocessingDocumentType.Document);
}
File.WriteAllBytes(@"c:\Templates\TemplateTestOutput.docx", stream.GetBuffer());
return;
}
它成功地創建了文件,但問題是,每當我打開新的 docx 文件時,它都會出現“Word Found Unreadable Content”錯誤。 我制作的模板並不復雜,它只有 3 個帶有常規標簽文本的內容控件。 我還嘗試使用僅幾行文本復制常規 docx,同樣的錯誤。
每當我單擊確定時,在 Word Found Unreadable Content 錯誤上,它顯示文檔就好了。 我不確定自己做錯了什么,此時我什至沒有編輯任何內容。
想出了一個解決辦法。
而不是使用 File.WriteAllBytes
File.WriteAllBytes(@"C:\\Templates\TemplateTestOutput.docx", stream.GetBuffer());
我使用了以下代碼:
using (FileStream fileStream = new FileStream(@"C:\\Templates\TemplateTestOutput.docx", System.IO.FileMode.CreateNew))
{
stream.WriteTo(fileStream);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.