Wednesday 11 June 2014

Export listview data to excel in C#.net



Create a windows application

Step 1: Add a reference (Microsoft.office.Interop.Excel)


Step 2: Add namespace and assign to ExcelAutomation

 
 
Step 3: Button Click Event write the below code: (lsvMinutes is the Listview Name)

ExcelAutomation.Application excelApp = new ExcelAutomation.ApplicationClass();
try
{
object Nullobj = System.Reflection.Missing.Value;
excelApp.UserControl = true;
ExcelAutomation.Workbook workbook = excelApp.Workbooks.Add(Type.Missing);
ExcelAutomation.Worksheet worksheet = (ExcelAutomation.Worksheet)workbook.Worksheets.get_Item(1);
worksheet.Name = "Minutes Report";

//headers
foreach (ColumnHeader columnheader in lsvMinutes.Columns)
{
worksheet.Cells[1, columnheader.Index + 1] = columnheader.Text;
}
string[] letters = new string[26] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
for (int i = 0; i < lsvMinutes.Columns.Count; i++)
{
string headerCell = letters.GetValue(i) + "1";
worksheet.get_Range(headerCell, headerCell).Font.Bold = true;
BorderCell(worksheet.get_Range(headerCell, headerCell));
worksheet.get_Range(headerCell, headerCell).Interior.ColorIndex = 24;
}
//content
for (int i = 0; i < lsvMinutes.Items.Count; i++)
{
for (int j = 0; j < lsvMinutes.Columns.Count; j++)
{
string dataCell = letters.GetValue(j) + (i + 2).ToString();
worksheet.Cells[i + 2, j + 1] = lsvMinutes.Items[i].SubItems[j].Text;
}
}
worksheet.Columns.AutoFit();
worksheet.Columns.HorizontalAlignment = ExcelAutomation.XlHAlign.xlHAlignLeft;
excelApp.Visible = true;

Release(worksheet);
Release(excelApp);
worksheet = null;
excelApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch (Exception ex)
{
ExceptionHandler.HandleException(ex.ToString());
}

Step 4: Give border to the excel sheet write the below code

private static void BorderCell(ExcelAutomation.Range CellRange)
{
CellRange.BorderAround(ExcelAutomation.XlLineStyle.xlContinuous,
ExcelAutomation.XlBorderWeight.xlThin,
ExcelAutomation.XlColorIndex.xlColorIndexAutomatic, Type.Missing);
}

Step 5: Release the excel object from the memory write the below code

private static void Release(object obj)
{
 try
 {
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj);
 }
 catch (Exception ex)
 {
ExceptionHandler.HandleException(ex.ToString());
 }
}

No comments: