导出DataGridView到Excel保存对话框

本文关键字:保存 对话框 Excel DataGridView 导出 | 更新日期: 2023-09-27 17:54:28

我想用保存对话框导出DataGridView到Excel文档。有人能帮忙吗?(注意:我想在Excel文档中的网格中存在的列名)

导出DataGridView到Excel保存对话框

我推荐EPPlus,它不需要在服务器上拥有办公室许可证。

private void btnExportToExcel_Click(object sender, EventArgs e)
{
    var dia = new System.Windows.Forms.SaveFileDialog();
    dia.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    dia.Filter = "Excel Worksheets (*.xlsx)|*.xlsx|xls file (*.xls)|*.xls|All files (*.*)|*.*";
    if(dia.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
    {
        DataTable data = null;// use the DataSource of the DataGridView here
        var excel = new OfficeOpenXml.ExcelPackage();
        var ws = excel.Workbook.Worksheets.Add("worksheet-name");
        // you can also use LoadFromCollection with an `IEnumerable<SomeType>`
        ws.Cells["A1"].LoadFromDataTable(data, true, OfficeOpenXml.Table.TableStyles.Light1);
        ws.Cells[ws.Dimension.Address.ToString()].AutoFitColumns();
        using(var file = File.Create(dia.FileName))
            excel.SaveAs(file);
    }
}