ListView to Excel Code (but needs SPEED improvements)

S

SVD

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.xlWBATWorksheet);
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();
}
 
J

James Westgate [Crainiate]

Im not sure if there is a specific reason for the GC.Collect at the end of
the code but garbage collection is an expensive operation. You can leave
garbage colletion to be handled automatically by the framework (when there
is a low demand for resources).

James
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top