Click here to Skip to main content
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 OriginalGriff 584
1 Maciej Los 275
2 DamithSL 233
3 Sergey Alexandrovich Kryukov 209
4 BillWoodruff 200
0 OriginalGriff 6,803
1 Sergey Alexandrovich Kryukov 6,377
2 DamithSL 5,421
3 Manas Bhardwaj 4,841
4 Maciej Los 4,330


Advertise | Privacy | Mobile
Web02 | 2.8.1411023.1 | Last Updated 20 May 2013
Copyright © CodeProject, 1999-2014
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