前置準備
- 安裝 Microsoft Office (含 Word)
- 專案加入參考:
Microsoft.Office.Interop.Word (COM 索引標籤)
- 引用命名空間:
using Word = Microsoft.Office.Interop.Word;
完整產生報表程式碼
public bool CreateWordReport(string filePath, List tasks) {
object missing = Type.Missing;
Word.Application app = null;
Word.Document doc = null;
try {
app = new Word.Application { Visible = false };
doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);
// 頁首
app.ActiveWindow.View.Type = Word.WdViewType.wdOutlineView;
app.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekPrimaryHeader;
app.Selection.TypeText("專案任務匯出報表");
app.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
app.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
// 標題
var titlePara = doc.Content.Paragraphs.Add(ref missing);
titlePara.Range.Text = "任務清單";
titlePara.Range.Font.Bold = 1;
titlePara.Range.Font.Size = 20;
titlePara.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
titlePara.Format.SpaceAfter = 12;
titlePara.Range.InsertParagraphAfter();
// 表格
foreach (var t in tasks) {
var table = doc.Tables.Add(doc.Bookmarks.get_Item(ref missing).Range, 5, 4, ref missing, ref missing);
table.Borders.Enable = 1;
table.Columns[1].Width = 60;
table.Columns[2].Width = 145;
table.Columns[3].Width = 80;
table.Columns[4].Width = 145;
FillCell(table, 1, 1, "專案名稱"); FillCell(table, 1, 2, t.ProjectName);
FillCell(table, 1, 3, "模組名稱"); FillCell(table, 1, 4, t.ModuleName);
FillCell(table, 2, 1, "負責人"); FillCell(table, 2, 2, t.Owner);
FillCell(table, 2, 3, "狀態"); FillCell(table, 2, 4, t.Status);
FillCell(table, 3, 1, "發布時間"); FillCell(table, 3, 2, t.ReleaseDate);
FillCell(table, 3, 3, "預計完成"); FillCell(table, 3, 4, t.DueDate);
FillCell(table, 4, 1, "實際完成"); FillCell(table, 4, 2, t.FinishDate);
FillCell(table, 4, 3, "分派人"); FillCell(table, 4, 4, t.Assigner);
FillCell(table, 5, 1, "任務描述");
table.Cell(5, 2).Merge(table.Cell(5, 4));
table.Cell(5, 2).Range.Text = t.Description;
}
doc.SaveAs2(filePath, Word.WdSaveFormat.wdFormatDocumentDefault);
return true;
} catch (Exception ex) {
Log.Error(ex);
return false;
} finally {
doc?.Close(ref missing, ref missing, ref missing);
app?.Quit(ref missing, ref missing, ref missing);
// 強制釋放 COM 物件
System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
GC.Collect(); GC.WaitForPendingFinalizers();
}
}
void FillCell(Word.Table table, int row, int col, string text) {
table.Cell(row, col).Range.Text = text;
}
關鍵注意事項
- COM 物件釋放:務必
ReleaseComObject + GC.Collect,否則 Word 進程殘留
- 版本獨立:使用
wdFormatDocumentDefault 自動對應 .docx/.doc
- 效能:Interop 呼叫跨程序邊界極慢,大量資料建議改用 Open XML SDK 或 DocX 純 .NET 庫
- 伺服器端:不建議在無人值守伺服器執行 Word Interop (Microsoft 不支援)
現代替代方案
- DocumentFormat.OpenXml:官方 SDK,直接操作 OOXML,無 Office 相依
- DocX (NuGet):語法友善的 Open XML 封裝
- NPOI:支援 .doc/.xls 與 .docx/.xlsx