Click here to Skip to main content
11,479,841 members (47,754 online)
Rate this: bad
Please Sign up or sign in to vote.
How to export DataGridview to Excel with Headers?
How to export cells selected(DataGridview) to Excel?
Posted 31-Jan-13 10:56am
Edited 31-Jan-13 10:57am
Sergey Alexandrovich Kryukov at 31-Jan-13 15:59pm
What did you try so far? Where is the problem: working with DataGridView? working with Excel? what?
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

private void button1_Click(object sender, EventArgs e)
            //connect with database
            OleDbConnection connection = new OleDbConnection();
            connection.ConnectionString = @"Provider=""Microsoft.Jet.OLEDB.4.0"";Data Source=""demo.mdb"";User Id=;Password=";
            OleDbCommand command = new OleDbCommand();
            command.CommandText = "select * from parts where Cost<1000 and ListPrice>500";
            DataSet dataSet = new System.Data.DataSet();
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command.CommandText, connection);
            DataTable dt = dataSet.Tables[0];
            this.dataGridView1.DataSource = dt;
            //export specific data to Excel
            Workbook book = new Workbook();
            Worksheet sheet = book.Worksheets[0];
            book.Worksheets[0].InsertDataTable(this.dataGridView1.DataSource as DataTable, true, 1, 1);
            book.SaveToFile("sample.xlsx", ExcelVersion.Version2010);

Code from this article:[^]
ghayour5 at 1-Feb-13 11:57am
Error in line "Workbook book = new Workbook();"
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

I am using this code for export datagridview to Excel:
Export DataGridView to Excel in 2.0 Windows Form[^]

But How to export DataGridview's Headers to Excel? (Picture)

Also How to export cells selected(DataGridview) to Excel? (Picture)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 260
1 Sergey Alexandrovich Kryukov 215
2 F-ES Sitecore 175
3 Richard MacCutchan 100
4 DamithSL 65
0 Sergey Alexandrovich Kryukov 7,890
1 OriginalGriff 7,556
2 Sascha Lefèvre 3,064
3 Maciej Los 2,491
4 Richard Deeming 2,335

Advertise | Privacy | Mobile
Web04 | 2.8.150520.1 | Last Updated 20 May 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100