Click here to Skip to main content
11,410,118 members (62,320 online)
Rate this: bad
good
Please Sign up or sign in to vote.
Hi
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
v2
Comments
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?
—SA
Rate this: bad
good
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);
            dataAdapter.Fill(dataSet);
            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);
            System.Diagnostics.Process.Start("sample.xlsx");
        }

Code from this article: http://www.c-sharpcorner.com/UploadFile/83fe73/solutions-to-export-data-from-database-to-excel-in-C-Sharp/[^]
  Permalink  
Comments
ghayour5 at 1-Feb-13 11:57am
   
Error in line "Workbook book = new Workbook();"
Rate this: bad
good
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 vb.net 2.0 Windows Form[^]

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

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

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 169
1 OriginalGriff 70
2 BillWoodruff 70
3 Maciej Los 68
4 Philippe Mori 60
0 Sergey Alexandrovich Kryukov 8,755
1 OriginalGriff 6,915
2 Maciej Los 3,390
3 Abhinav S 3,248
4 Peter Leow 3,059


Advertise | Privacy | Mobile
Web01 | 2.8.150414.5 | 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