萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 使用 Aspose.Words 導出 Word 文檔完整實戰

方案優勢

Aspose.Words 是強大的文檔處理庫,無需服務器安裝 Office 組件即可在服務端生成、轉換、操作 Word 文檔,適合自動化報表、合同生成等場景。

核心實現步驟

1. 環境準備與文檔初始化

// 生成唯一文件名
Random rd = new Random();
DateTime dtime = DateTime.Now;
string fileName = $"培訓需求表{dtime:yyyyMMddHHmmss}{rd.Next(99) * 97 + 100}.doc";

// 載入模板
string templatePath = Constants.GetAppSettingValue("LocalLogicPath") 
                    + Constants.GetAppSettingValue("LocalTemplate") 
                    + "px_xqjh_tx.doc";
Document doc = new Document(templatePath);
DocumentBuilder builder = new DocumentBuilder(doc);

2. 頁面佈局配置

builder.PageSetup.PaperSize = PaperSize.A4;
// builder.PageSetup.Orientation = Orientation.Landscape; // 橫向可選

3. 全局樣式設置

builder.RowFormat.Borders.LineStyle = LineStyle.Thick;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.RowFormat.Alignment = RowAlignment.Center;
builder.Font.Name = "宋體";
builder.Font.Size = 10.5; // 五號字

4. 動態表格構建

// 獲取模板表格列寬
List<double> widthList = new List<double>();
double remarkWidth = 0;
for (int k = 0; k < 18; k++) {
    builder.MoveToCell(0, 1, k, 0);
    double width = builder.CellFormat.Width;
    widthList.Add(width);
    remarkWidth += width;
}

// 填充數據
DataTable dt = GetQuestionList();
if (dt != null && dt.Rows.Count > 0) {
    // 書籤定位
    doc.Range.Bookmarks["tbdw"].Text = lblcom.Text;
    builder.MoveToBookmark("pxtx");
    
    // 開始構建表格
    Table table = builder.StartTable();
    builder.RowFormat.HeadingFormat = true;
    builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
    
    // 數據行
    for (int i = 0; i < dt.Rows.Count; i++) {
        for (int j = 0; j < dt.Columns.Count - 3; j++) {
            builder.InsertCell();
            // 單元格格式化
            builder.CellFormat.Borders.LineStyle = LineStyle.Single;
            builder.CellFormat.Borders.Color = Color.Black;
            builder.CellFormat.Width = widthList[j];
            builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Top;
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
            builder.Write(dt.Rows[i][j].ToString().Trim());
        }
        builder.EndRow();
    }
    
    // 備註列
    builder.InsertCell();
    builder.CellFormat.Width = remarkWidth;
    builder.RowFormat.Height = 50;
    builder.Write("備注:");
    builder.EndRow();
    
    // 結尾處理
    builder.EndTable();
    doc.Range.Bookmarks["pxtx"].Text = "";
    
    // 簽名信息
    doc.Range.Bookmarks["writername"].Text = dt.Rows[0]["reg_staff_name"].ToString();
    doc.Range.Bookmarks["checkname"].Text = dt.Rows[0]["check_man_name"].ToString();
}
dt.Dispose();

5. 文檔輸出

doc.Save(fileName, SaveFormat.Doc, SaveType.OpenInWord, Response);

關鍵技術點總結

  • 模板驅動:使用書籤定位動態內容區域,分離模板與數據
  • 精確佈局:預讀列寬保證生成表格與模板一致
  • 樣式統一:全局字體、邊框、對齊設置確保專業外觀
  • 資源釋放:DataTable.Dispose() 及時釋放非託管資源

此方案實現了服務端無 Office 依賴的專業級 Word 導出,代碼結構清晰,易於維護擴展。

copyright © 萬盛學電腦網 all rights reserved