[C#] 使用 ClosedXML將DataGridView 匯出至 Excel
使用 ClosedXML將DataGridView 匯出至 Excel
using ClosedXML.Excel;
public void ExportToExcel()
{
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("Sheet1");
// 匯出 DataGridView 標題
for (int col = 0; col < dataGridView1.Columns.Count; col++)
{
ws.Cell(1, col + 1).Value = dataGridView1.Columns[col].HeaderText;
}
// 匯出 DataGridView 內容
for (int row = 0; row < dataGridView1.Rows.Count; row++)
{
for (int col = 0; col < dataGridView1.Columns.Count; col++)
{
var cellValue = dataGridView1.Rows[row].Cells[col].Value;
ws.Cell(row + 2, col + 1).Value = cellValue != null ? cellValue.ToString() : "";
}
}
// 儲存 Excel
wb.SaveAs(@"C:\Temp\Data.xlsx");
MessageBox.Show("Excel 匯出完成!");
}
參考網址:
By Hao★
留言
張貼留言
歡迎留言