C# DataGridview 导出到 Excel:简单代码示例
以下是在 C# 中将 DataGridView 导出到 Excel 的代码示例:
private void ExportToExcel(DataGridView dataGridView)
{
// 创建 Excel 对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
// 循环 DataGridView 中的行和列,并将其添加到 Excel 中
int rowIndex = 1;
foreach (DataGridViewRow row in dataGridView.Rows)
{
int columnIndex = 1;
foreach (DataGridViewCell cell in row.Cells)
{
excel.Cells[rowIndex, columnIndex] = cell.Value;
columnIndex++;
}
rowIndex++;
}
// 保存 Excel 文件
excel.ActiveWorkbook.SaveCopyAs(@"C:\Users\user\Desktop\DataGridViewExport.xlsx");
excel.ActiveWorkbook.Saved = true;
excel.Quit();
}
该方法将 DataGridView 作为参数传入,并创建一个 Excel 对象。然后,它循环遍历 DataGridView 的行和列,并将它们添加到 Excel 中。最后,它将 Excel 文件保存到指定位置。
原文地址: https://www.cveoy.top/t/topic/nGTt 著作权归作者所有。请勿转载和采集!