-1

I want to Export the DataGridView to Excel Document with a save dialog. can anyone help? (Note: I want the column names which are present in the Grid in the Excel Document)

Varun
  • 81
  • 2
  • 6
  • 3
    Your question could result in an entire chapter tutorial. What exactly are you having trouble with? – lc. Jan 18 '13 at 15:37
  • There are many references to this exact topic available via a web search. A good place to start is http://www.codeproject.com/Tips/472706/Export-DataGridView-to-Excel – dash Jan 18 '13 at 15:39

1 Answers1

8

I would recommend EPPlus which doesn't require to have an office-license on the server.

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);
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939