Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
C# Export DataGridView to Excel Sheet
WhatsApp
Kishan Tanpure
Sep 22
2014
17.5
k
0
2
using
Microsoft.Office.Interop.Excel;
//Create a Button btnExport on your form and write following code on its Click Event
private
void
btnExport_Click(
object
sender, EventArgs e)
{
SaveFileDialog sfd =
new
SaveFileDialog();
DialogResult drSaveFile = sfd.ShowDialog();
try
{
if
(drSaveFile == System.Windows.Forms.DialogResult.OK)
{
ApplicationClass ExcelApp =
new
ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
//ExcelApp.ActiveWorkbook.FileFormat = XlFileFormat.xlExcel8;
// Change properties of the Workbook
ExcelApp.Columns.ColumnWidth = 20;
// Storing header part in Excel
for
(
int
i = 1; i < datagridview.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = datagridview.Columns[i - 1].HeaderText;
}
// Storing Each row and column value to excel sheet
for
(
int
i = 0; i < datagridview.Rows.Count; i++)
{
for
(
int
j = 0; j < datagridview.Columns.Count; j++)
{
if
(j == 2 || j == 5)
{
ExcelApp.Cells[i + 2, j + 1] =
"'"
+ datagridview.Rows[i].Cells[j].Value.ToString();
}
else
{
ExcelApp.Cells[i + 2, j + 1] = datagridview.Rows[i].Cells[j].Value.ToString();
}
}
}
//Save Copy by giving file Path
//ExcelApp.ActiveWorkbook.SaveCopyAs("C:\\" + FileName);
//OR using SaveFileDialog
ExcelApp.ActiveWorkbook.SaveCopyAs(sfd.FileName);
//OR even you can use SaveAs function
//ExcelApp.ActiveWorkbook.SaveAs(sfd.FileName, XlFileFormat.xlExcel8, null, null, null,
// null, XlSaveAsAccessMode.xlShared, null, null, null, null, null);
ExcelApp.ActiveWorkbook.Saved =
true
;
ExcelApp.Quit();
}
}
catch
(Exception ex)
{
MessageBox.Show(
"ERROR: "
+ ex.Message);
}
}
DataGridView
Excel
Up Next
C# Export DataGridView to Excel Sheet