I have a datatable in my application. Now I want to export the table into excel file by clicking a button in form. Please help me. I never export anything to excel before in C#.
Microsoft.Office.Interop.Excel.ApplicationClass excel = new ApplicationClass();
excel.Application.Workbooks.Add(true);
for (int col = 0; col<lstView.Columns.Count;col++ )
{
excel.Cells[1, col + 1] = lstView.Columns[col].Text.ToString();
}
int rowIndex = 1;
int row = 0;
for (row=0; row <lstView.Items.Count;row++)
{
if (rowIndex <= lstView.Items.Count)
rowIndex++;
for (int col = 0; col < lstView.Columns.Count; col++)
{
excel.Cells[rowIndex, col + 1] = lstView.Items[row].SubItems[col].Text.ToString();
}
}
tmpRow = row;
tmpItx = rowIndex;
for (row = 0; row < lstViewPdf.Items.Count; row++)
{
if (tmpItx <= (lstViewPdf.Items.Count * 2))
tmpItx++;
for (int col = 0; col < lstViewPdf.Columns.Count; col++)
{
excel.Cells[tmpItx, col + 1] = lstViewPdf.Items[row].SubItems[col].Text.ToString();
}
}
Worksheet worksheet = (Worksheet)excel.ActiveSheet;
worksheet.Activate();
worksheet.SaveAs("D:\\Inputs\\test.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excel.Workbooks.Close();
excel.Quit();
MessageBox.Show("Process completed");
Before export the data you should load the data from database to a listview control and then export it to excel.
I make use of this code to export data to excel and it is working fine.