View Single Post
  #1   Report Post  
Posted to microsoft.public.dotnet.framework.windowsforms,microsoft.public.dotnet.framework.windowsforms.controls,microsoft.public.excel.programming
SVD SVD is offline
external usenet poster
 
Posts: 1
Default ListView to Excel Code (but needs SPEED improvements)

Hi,

The following code works, but it has some issues:

1) Any suggestions to optimize the code?
2) How can I set the text and background colors for my header cells

Thanks,

Steve


private void button1_Click(object sender, System.EventArgs e)
{
// Create application
Excel.Application excel = new Excel.Application();

if (excel == null)
{
MessageBox.Show("ERROR: EXCEL could not be started!");
return;
}

// Add 1 workbook with 1 sheet
Excel.Workbook workbook =
excel.Workbooks.Add(Excel.XlWBATemplate.xlWBATWork sheet);
Excel.Worksheet workSheet =
(Excel.Worksheet)workbook.ActiveSheet;

// Add column headers
for (int columnIndex=0; columnIndex<listView1.Columns.Count;
columnIndex++)
{
workSheet.Cells[1, columnIndex+1] =
listView1.Columns[columnIndex].Text;
((Excel.Range)(workSheet.Cells[1, columnIndex+1])).Font.Bold
= true;
}

// Add data rows
for (int rowIndex=0; rowIndex<listView1.Items.Count; rowIndex++)
{
for (int columnIndex=0; columnIndex<listView1.Columns.Count;
columnIndex++)
{
workSheet.Cells[rowIndex+2, columnIndex+1] =
listView1.Items[rowIndex].SubItems[columnIndex].Text;
}
}

// Autofit
workSheet.Columns.AutoFit();

// Show
excel.Visible = true;

// Clean up
excel = null;
workBook = null;
workSheet = null;
GC.Collect();
}