方法一:模板置換法(彈性高、推薦)
1. 準備模板 template.htm
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>$title$ - 靜態頁示例</title>
<style>.STYLE1 { font-size:16px; font-weight:bold; }</style>
</head>
<body>
<table width="100%" border="0" bgcolor="#339900">
<tr><td height="34" align="center" bgcolor="#FFFFFF"><span class="STYLE1">$title$</span></td></tr>
<tr><td height="42" bgcolor="#FFFFFF">內容:$content$</td></tr>
</table>
</body>
</html>
2. 後端產生程式碼
protected void btnGenerate_Click(object sender, EventArgs e)
{
string templatePath = Server.MapPath("template.htm");
Encoding encoding = Encoding.GetEncoding("utf-8"); // 建議 UTF-8
string template;
using (StreamReader sr = new StreamReader(templatePath, encoding))
template = sr.ReadToEnd();
// 置換標記
template = template.Replace("$title$", txtTitle.Text);
template = template.Replace("$content$", txtContent.Text);
// 輸出檔案
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".htm";
string outputPath = Server.MapPath("~/htm/") + fileName;
using (StreamWriter sw = new StreamWriter(outputPath, false, encoding))
{
sw.Write(template);
}
Response.Write($"<a href='htm/{fileName}' target='_blank'>{fileName}</a> 已產生於 htm 資料夾。");
}
方法二:URL 直接抓取法(快速但彈性低)
protected void btnGenerateByUrl_Click(object sender, EventArgs e)
{
Encoding encoding = Encoding.GetEncoding("utf-8");
string url = txtUrl.Text.Trim(); // 目標動態頁面完整 URL
WebRequest req = WebRequest.Create(url);
using (WebResponse resp = req.GetResponse())
using (StreamReader sr = new StreamReader(resp.GetResponseStream(), encoding))
{
string html = sr.ReadToEnd();
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".htm";
string outputPath = Server.MapPath("~/htm/") + fileName;
using (StreamWriter sw = new StreamWriter(outputPath, false, encoding))
sw.Write(html);
Response.Write($"<a href='htm/{fileName}' target='_blank'>{fileName}</a> 已產生。");
}
}
比較與選擇建議
| 維度 | 模板置換法 | URL 抓取法 |
| 內容控制 | 精確控制每個欄位 | 完整複製輸出 HTML |
| 動態資料 | 需自行查詢組裝 | 直接利用現有頁面邏輯 |
| 效能 | 較快(無 HTTP 往返) | 需發出 HTTP Request |
| 適用場景 | 新聞發布、商品頁、部落格文章 | 快速轉換現有動態頁、原型驗證 |
進階考量
- 大量靜態檔案需規劃目錄結構(如 /htm/yyyy/MM/)。
- 搭配 CDN 快取靜態資源,降低伺服器負載。
- 需支援分頁時,可在模板中預留分頁區塊,產生時一併渲染。