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
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Shafiqq Aziz
NA
54
12.2k
C# Export DataGridView to Excel
Nov 8 2017 10:27 PM
Hi all,
I'm using this (https://code.msdn.microsoft.com/office/How-to-Export-DataGridView-62f1f8ff) to create export to excel process.
I've encountered a problem where my first row of data does not exported to excel. And I think i'm not missing any line of codes provided in the tutorial. Can you guys help me out with this problem?
Here's my exported data.
And here's my codes.
private
void
ExportToExcel()
{
Microsoft.Office.Interop.Excel._Application excel =
new
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet =
null
;
try
{
worksheet = workbook.ActiveSheet;
worksheet.Name =
"Exported From DataGrid"
;
int
cellRowIndex = 1;
int
cellColumnIndex = 1;
for
(
int
i = 0; i < dataGridView2.Rows.Count - 1; i++)
{
for
(
int
j = 0; j < dataGridView2.Columns.Count; j++)
{
if
(cellRowIndex == 1)
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView2.Columns[j].HeaderText;
}
else
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView2.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}
SaveFileDialog saveDialog =
new
SaveFileDialog();
saveDialog.Filter =
"Excel files (*.xlsx)|*.xlsx"
;
saveDialog.FilterIndex = 1;
if
(saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show(
"Export Successful!"
);
}
}
catch
(System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excel.Quit();
workbook =
null
;
excel =
null
;
}
}
Reply
Answers (
4
)
Generate RDLC report using LINQ
Add Windows Form Login Page