C# Winform 中DataGridView数据集通过EPPlus导出excel到本地
/// <summary>
/// 查询数据导出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGridExport_Click(object sender, EventArgs e)
{
if (gridList.Rows.Count > 0)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Excel Files|*.xlsx";
saveFileDialog.Title = "Save an Excel File";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
ExportDataGridViewToExcel(filePath);
}
}
}
else
{
MessageBox.Show("当前没有需要导出的数据");
}
}
private void ExportDataGridViewToExcel(string filePath)
{
// 设置 EPPlus 的许可上下文
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Data");
// 添加列标题
for (int i = 0; i < gridList.Columns.Count; i++)
{
worksheet.Cells[1, i + 1].Value = gridList.Columns[i].HeaderText;
}
// 添加行数据
for (int i = 0; i < gridList.Rows.Count; i++)
{
for (int j = 0; j < gridList.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1].Value = gridList.Rows[i].Cells[j].Value;
}
}
// 自动调整列宽
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
// 保存到文件
using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
package.SaveAs(stream);
}
}
MessageBox.Show("导出成功!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}