簡體   English   中英

ASP.NET + C#。 從模板創建Word文檔

[英]ASP.NET + C#. Creating word document from template

我有一個Word文檔,其中僅包含一頁文字和圖形。 該頁面還包含一些占位符,例如[Field1],[Field2],...等。我從數據庫中獲取數據,我想打開此文檔並用一些數據填充占位符。 對於要打開此文檔的每個數據行,請在占位符中填充該行的數據,然后將所有創建的文檔連接到一個文檔中。 最佳和最簡單的方法是什么?

而不是第三方,我建議您使用openXML

添加以下名稱空間System.Text.RegularExpressions; DocumentFormat.OpenXml.Packaging; 和DocumentFormat.OpenXml.Wordprocessing;

    public static void SearchAndReplace(string document)
   {
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
    string docText = null;
    using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
    {
        docText = sr.ReadToEnd();
    }

    Regex regexText = new Regex("Hello world!");
    docText = regexText.Replace(docText, "Hi Everyone!");

    using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
    {
        sw.Write(docText);
    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM