TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
C# Export DataGridView to Excel Sheet
Kishan Tanpure
Sep 22
2014
Code
17.1
k
0
2
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
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