C# export data form gridview to excel sheet.
How to export data form gridview to excel in .xlsx extention ?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Nanhe SiddiquePosted May 9, 2015, 12:04 AM
http://www.aspdotnet-suresh.com/2011/04/how-to-export-gridview-data-to-excel-or.html
it may halps
Dipankar BiswasPosted May 8, 2015, 11:04 PM
using System.Reflection;
using iTextSharp.text;
using ClosedXML.Excel;
private void button1_Click(object sender, EventArgs e)
{
//Creating DataTable
DataTable dt = new DataTable();
//Adding the Columns
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
dt.Columns.Add(column.HeaderText, column.ValueType);
}
//Adding the Rows
foreach (DataGridViewRow row in dataGridView1.Rows)
{
dt.Rows.Add();
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value != null)
{
dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
}
}
}
//Exporting to Excel
string folderPath = "D:\\Excel\\";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt, "Customers");
wb.SaveAs(folderPath + "DataGridViewExport.xlsx");
}
}