Aspose.Words 是強大的文檔處理庫,無需服務器安裝 Office 組件即可在服務端生成、轉換、操作 Word 文檔,適合自動化報表、合同生成等場景。
// 生成唯一文件名
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);
builder.PageSetup.PaperSize = PaperSize.A4;
// builder.PageSetup.Orientation = Orientation.Landscape; // 橫向可選
builder.RowFormat.Borders.LineStyle = LineStyle.Thick;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.RowFormat.Alignment = RowAlignment.Center;
builder.Font.Name = "宋體";
builder.Font.Size = 10.5; // 五號字
// 獲取模板表格列寬
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();
doc.Save(fileName, SaveFormat.Doc, SaveType.OpenInWord, Response);
DataTable.Dispose() 及時釋放非託管資源此方案實現了服務端無 Office 依賴的專業級 Word 導出,代碼結構清晰,易於維護擴展。