Tech
Forums
Jobs
Books
Events
Videos
Live
More
Interviews
Certification
Training
Career
Members
News
Blogs
Contribute
An Article
A Blog
A Video
An Ebook
An Interview Question
Register
Login
4
Answers
C# Export DataGridView to Excel
Shafiqq Aziz
7y
289
1
Reply
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
;
}
}
Post
Reset
Cancel
Answers (
4
)
Next Recommended Forum
Generate RDLC report using LINQ
Add Windows Form Login Page