C# export data form gridview to excel sheet.
How to export data form gridview to excel in .xlsx extention ?
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Dipankar BiswasRank #992 · 2K reputationPosted May 8, 2015, 7:04 PM EDT
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");
}
}
Nanhe SiddiqueRank #1,103 · 1.7K reputationPosted May 8, 2015, 8:04 PM EDT
http://www.aspdotnet-suresh.com/2011/04/how-to-export-gridview-data-to-excel-or.html
it may halps