I am trying to export my ListView items to excel file
But when I tried to use backgroundworker to do the job without freezing my UI Window.
And error occurred when the process start to loop through the items.
Here is my code under bagcroundworker do_work event
cross thread error event at this point of code foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
I wonder why there is no cross thread error on my first loop.
But when I tried to use backgroundworker to do the job without freezing my UI Window.
And error occurred when the process start to loop through the items.
Here is my code under bagcroundworker do_work event
cross thread error event at this point of code foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
I wonder why there is no cross thread error on my first loop.
Code:
{
Excel.Application app = new Excel.Application();
app.Visible = true;
Workbook wb = app.Workbooks.Add(1);
Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);
Excel.Range rng;
rng = ws.get_Range("A9", "F9");
ws.get_Range("C3", "E3").Merge();
ws.get_Range("C4", "D4").Merge();
ws.get_Range("C5", "E5").Merge();
ws.Cells[3, 3] = "----------";
ws.Cells[4, 3] = "REPORT OF: ";
ws.Cells[5, 3] = "AS OF: " + DateTime.Today.Year.ToString();
ws.get_Range("B3", "F3").Font.Bold = true;
ws.get_Range("B3", "F3").Font.Size = 14;
rng.Interior.Color = Color.FromName("Teal");
rng.Font.Bold = true;
ws.Cells[lvResult.Items.Count + 12, 6] = "TOTAL: " + lvResult.Items.Count.ToString();
ws.Shapes.AddPicture(System.Windows.Forms.Application.StartupPath + "\\assets\\logo.png", MsoTriState.msoFalse, MsoTriState.msoTrue, 5, 10, 100, 100);
int i = 1;
int j = 11;
try
{
int k = 1;
foreach (ColumnHeader col in lvResult.Columns)
{
ws.Cells[9, k++] = col.Text;
}
foreach (ListViewItem lvi in lvResult.Items)
{
i = 1;
foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
{
Excel.Range r = (Excel.Range)ws.Cells[j, i];
r.Value = lvs.Text;
bgExport.ReportProgress(i / 100);
i++;
}
j++;
}
ws.Columns.AutoFit();
}
catch (Exception ex)
{
MessageBox.Show("Error encountered while exporting.\r\nExport will exit.\r\n" + ex.ToString(), "Warning");
}