Friday, July 16, 2010

Export data of Listview Control to excel file by using c#.net

Add the reference of the Microsoft Excel Object 12 reference into your project

then add the following code

Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();

xla.Visible = true;

Microsoft.Office.Interop.Excel.Workbook wb = xla.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);

Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xla.ActiveSheet;

int i = 1;

int j = 1;

foreach (ListViewItem comp in listView1.Items)

{

ws.Cells[i, j] = comp.Text.ToString();

//MessageBox.Show(comp.Text.ToString());

foreach (ListViewItem.ListViewSubItem drv in comp.SubItems)

{

ws.Cells[i, j] = drv.Text.ToString();

j++;

}

j = 1;

i++;

}