首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

使用 Aspose.Words for .NET 動態產生 Word 文件中的資料表格

     編輯:關於.NET

專案需求:匯出 Word 文件,格式由使用者自訂模板,表格欄位動態決定 (如僅勾選「姓名、性別」則僅匯出這兩欄)。Aspose.Words for .NET 不需安裝 Office、支援多種格式 (DOC/DOCX/PDF/HTML...),完美解決此需求。

核心概念:書籤 當作動態資料錨點

模板中在需填入資料處插入「書籤」,程式碼透過 Document.Range.Bookmarks 定位並寫入值。

Aspose.Words 架構圖 模板書籤範例

基本欄位填寫範例

string tmppath = Server.MapPath("~/template.doc");
Document doc = new Document(tmppath);
if (doc.Range.Bookmarks["name"] != null)
{
    Bookmark mark = doc.Range.Bookmarks["name"];
    mark.Text = "張三公司";
}
doc.Save("demo.doc", SaveFormat.Doc, SaveType.OpenInWord, Response);

動態表格進階實作

1. 模板設計

  • 建立一個表格,表頭列包含「所有可能欄位」。
  • 每個表頭儲存格內插入書籤,書籤名稱 = 欄位名稱 (如 ProductName、Price)。
  • 在表格下方插入一個書籤 table 作為資料列插入起點。
動態表格模板書籤佈局

2. 程式碼邏輯

DocumentBuilder builder = new DocumentBuilder(doc);
DataTable products = this.GetData(); // 資料來源
int count = 0;

// 1. 依據資料欄位清除不需顯示的表頭書籤,統計實際顯示欄數
for (int i = 0; i < products.Columns.Count; i++)
{
    string colName = products.Columns[i].ColumnName.Trim();
    if (doc.Range.Bookmarks[colName] != null)
    {
        Bookmark mark = doc.Range.Bookmarks[colName];
        mark.Text = ""; // 清空表頭文字 (稍後重填)
        count++;
    }
}

// 2. 依序讀取表頭列書籤名稱,建立欄位順序清單
List<string> listcolumn = new List<string>(count);
for (int i = 0; i < count; i++)
{
    builder.MoveToCell(0, 0, i, 0); // 移至表格(0) 第0列 第i欄
    if (builder.CurrentNode.NodeType == NodeType.BookmarkStart)
        listcolumn.Add((builder.CurrentNode as BookmarkStart).Name);
}

double width = builder.CellFormat.Width; // 保留欄寬
builder.MoveToBookmark("table"); // 移至資料插入點

// 3. 逐列寫入資料
for (int m = 0; m < products.Rows.Count; m++)
{
    for (int i = 0; i < listcolumn.Count; i++)
    {
        builder.InsertCell();
        builder.CellFormat.Borders.LineStyle = LineStyle.Single;
        builder.CellFormat.Borders.Color = Color.Black;
        builder.CellFormat.Width = width;
        builder.CellFormat.VerticalMerge = CellMerge.None;
        builder.Write(products.Rows[m][listcolumn[i]].ToString());
    }
    builder.EndRow();
}

doc.Range.Bookmarks["table"].Text = ""; // 清除標記
doc.Save("baojiadan.doc", SaveFormat.Doc, SaveType.OpenInWord, Response);

3. 產出結果

最終文件僅包含使用者勾選的欄位,格式完全套用模板樣式。

動態產出 Word 表格結果

總結

Aspose.Words 以 DocumentBuilder 操作文件 DOM,結合書籤定位,實現「模板外觀固定、欄位動態決定」的靈活報表產生。雖為商業套件,但功能強大、API 直覺,極適合企業級文件自動化需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved