I have a ListView
which after populating it, will look like this:
I already can export it to a CSV formatted file using the following code:
StringBuilder sb = new StringBuilder();
//Making columns!
foreach (ColumnHeader ch in lvCnt.Columns)
{
sb.Append(ch.Text + ",");
}
sb.AppendLine();
//Looping through items and subitems
foreach (ListViewItem lvi in lvCnt.Items)
{
foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
{
if (lvs.Text.Trim() == string.Empty)
sb.Append(" ,");
else
sb.Append(lvs.Text + ",");
}
sb.AppendLine();
}
But the problem is, in CSV, I can not export the back color of the ListView
items and subitems, which in my case are very important. Would be nice if you can help me with this or at least point me to the right direction!
UPDATE
I managed to find a way to export directly to Excel, but I still can not export the background color of ListView items into Excel.
private void ToExcel()
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(1);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];
int i = 1;
int i2 = 1;
foreach (ListViewItem lvi in myList.Items)
{
i = 1;
foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
{
ws.Cells[i2, i] = lvs.Text;
i++;
}
i2++;
}
}
The easy way to export a list view is to click on the printer icon in the top-right corner of the list view: this produces a pop-up window with a printable view. You then select the rows/columns, copy and then paste into Excel.
Select List, and then select Export to Excel. By default, this capability is enabled on external lists, but it can be disabled by a system administrator. If you are prompted to confirm the operation, select OK.
Seems like this is a pretty easy project to export your data with:
It has examples showing how to set background colours and other formatting items.
You already have your code to loop through the headers and rows so you should be able to work with it!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With