可以通过以下步骤实现:
using System;
using System.Data;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
private void CopyDataGridViewToExcel(DataGridView dataGridView)
{
// 创建Excel应用程序对象
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
// 创建一个新的工作簿
Excel.Workbook workbook = excelApp.Workbooks.Add();
Excel.Worksheet worksheet = workbook.ActiveSheet;
// 复制DataGridView的列标题到Excel
for (int i = 1; i <= dataGridView.Columns.Count; i++)
{
worksheet.Cells[1, i] = dataGridView.Columns[i - 1].HeaderText;
}
// 复制DataGridView的行数据到Excel
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
for (int j = 0; j < dataGridView.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView.Rows[i].Cells[j].Value.ToString();
}
}
// 自动调整列宽
worksheet.Columns.AutoFit();
// 释放Excel对象
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
worksheet = null;
workbook = null;
excelApp = null;
// 强制垃圾回收
GC.Collect();
}
CopyDataGridViewToExcel(dataGridView1);
这样,当前DataGridView的行数据将会被复制到一个新的Excel工作簿中。
领取专属 10元无门槛券
手把手带您无忧上云