How to Export data from DataGridView to excel in window form in asp.net with c#
How to Export data from DataGridView to excel in window form in asp.net with c#
Step 1: Add “saveFileDialog1” from Toolbar
Step 2: Add “button”
then write following code on button submit
saveFileDialog1.InitialDirectory = "C:";
saveFileDialog1.Title = "Save as Excel File";
saveFileDialog1.FileName = "";
saveFileDialog1.Filter = "Excel Files(2003)|*.xls|Excel
Files(2007)|*.xlsx";
if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
{
Microsoft.Office.Interop.Excel.Application ExcelApp = new
Microsoft.Office.Interop.Excel.Application();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth =
20;
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] =
dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if
(dataGridView1.Rows[i].Cells[j].Value != null)
{
ExcelApp.Cells[i +
2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs(saveFileDialog1.FileName.ToString());
ExcelApp.ActiveWorkbook.Saved =
true;
ExcelApp.Quit();
}
0 comments:
Post a Comment
Do not enter spam link