问题
I have a ListView
wich 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 atleast 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. Please help!
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++;
}
}
回答1:
Seems like this is a pretty easy project to export your data with:
- http://epplus.codeplex.com/wikipage?title=WebapplicationExample
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!
来源:https://stackoverflow.com/questions/8312239/exporting-a-listview-to-excel-format