Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting a ListView to Excel format

I have a ListView which after populating it, will look like this:

enter image description here

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++;
        }
}
like image 973
Saeid Yazdani Avatar asked Nov 29 '11 14:11

Saeid Yazdani


People also ask

Can I export a list view?

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.

How do I export a custom list in 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.


1 Answers

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!

like image 131
rtpHarry Avatar answered Sep 22 '22 01:09

rtpHarry