private void btnExportWord_Click(object sender, EventArgs e) {
if (dataGridView1.Rows.Count == 0) { MessageBox.Show("無資料"); return; }
SaveFileDialog sfd = new SaveFileDialog {
Filter = "Word 文件 (*.docx)|*.docx|Word 97-2003 (*.doc)|*.doc",
FileName = $"Export_{DateTime.Now:yyyyMMdd_HHmmss}.docx"
};
if (sfd.ShowDialog() != DialogResult.OK) return;
Word.Application wordApp = null;
Word.Document doc = null;
try {
wordApp = new Word.Application { Visible = false };
doc = wordApp.Documents.Add();
// 建立表格:列數 = 欄位數,行數 = 資料行數 + 1 (標題列)
int cols = dataGridView1.Columns.Count;
int rows = dataGridView1.Rows.Count + 1;
Word.Table table = doc.Tables.Add(wordApp.Selection.Range, rows, cols);
table.Borders.Enable = 1;
// 寫入標題列
for (int c = 0; c < cols; c++) {
table.Cell(1, c + 1).Range.Text = dataGridView1.Columns[c].HeaderText;
table.Cell(1, c + 1).Range.Bold = 1;
}
// 寫入資料列
for (int r = 0; r < dataGridView1.Rows.Count; r++) {
for (int c = 0; c < cols; c++) {
var val = dataGridView1.Rows[r].Cells[c].Value;
table.Cell(r + 2, c + 1).Range.Text = val?.ToString() ?? "";
}
}
// 自動調整欄寬
table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitWindow);
doc.SaveAs2(sfd.FileName);
MessageBox.Show("匯出成功!");
} catch (Exception ex) {
MessageBox.Show("失敗: " + ex.Message);
} finally {
if (doc != null) doc.Close(false);
if (wordApp != null) wordApp.Quit(false);
// 釋放 COM 物件
System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
GC.Collect(); GC.WaitForPendingFinalizers();
}
}
建議:客戶端桌面程式且環境可控用 Interop 功能最全;伺服器端/無 Office 環境請用 DocX 或 Open XML SDK。