2020-06-09
建立 C:\Temp\Test.docx 檔案,裡面放一個字串 {$name}
本程式會把該字串替換掉。
NuGet 安裝 NPOI 元件。
Default.aspx
Default.aspx.cs
測試
NuGet 安裝 NPOI 元件。
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WordDocxReplaceByNPOI.Default" %> <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html> |
Default.aspx.cs
using System; using System.IO;
namespace WordDocxReplaceByNPOI
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
// 限制 Word 2007 或以上的 .docx文件
FileStream fs = new FileStream(@"C:\Temp\test.docx", FileMode.Open, FileAccess.Read);
NPOI.XWPF.UserModel.XWPFDocument myDocx = new NPOI.XWPF.UserModel.XWPFDocument(fs);
foreach (var para in myDocx.Paragraphs)
{
string oldtext = para.ParagraphText;
string newText = "趙錢孫";
if (oldtext == "")
continue;
string temptext = para.ParagraphText;
//以下為替換文件模版中的關鍵字
if (temptext.Contains("{$name}"))
temptext = temptext.Replace("{$name}", newText);
para.ReplaceText(oldtext, temptext);
}
FileStream output = new FileStream(@"C:\Temp\test2.docx", FileMode.Create);
myDocx.Write(output);
fs.Close();
fs.Dispose();
output.Close();
output.Dispose();
}
}
} |
測試
2020-06-15 補充,在 "樣張1.docx" 上使用,出現錯誤
把 "樣張1.docx" 改名 "樣張1.docx.zip",解壓,用IE11檢視 /word/document.xml,沒有錯誤訊息。
把 "樣張2.docx" 改名 "樣張2.docx.zip",解壓,用IE11檢視 /word/document.xml,沒有錯誤訊息。
兩者的結構是有些不同,但 IE11 檢視都沒有報錯誤,暫時不知如何解。
也就是程式無法試用於各種 .docx 情況。
(完)
相關
[研究][C#][ASP.NET] 用 NPOI 替換 Word (.docx) 中的文字
[研究][C#][ASP.NET] 用 DocXCore 1.0.7 ( Novacode ) 替換 Word (.docx) 中的文字
[研究][C#][ASP.NET] 用 DocX 1.6.0 ( Xceed Words for .NET) 替換 Word (.docx) 中的文字


感謝教學~
回覆刪除