views:

2757

answers:

2

Is anyone aware of a decent CSV export tool for exporting from a ListView? I'm in a mad rush to get a project update out and feature creep means I don't have time to get this final urgent feature implemented myself.

+2  A: 

FileHelpers is a nice library that might just be your best friend today

second
+8  A: 

That's not a big feature I'd say, unless you have some very odd requirements... but in this case, probably, no external tool can help you anyway.

Here is how I would approach the problem:

class ListViewToCSV
{
    public static void ListViewToCSV(ListView listView, string filePath, bool includeHidden)
    {
        //make header srting
        StringBuilder result = new StringBuilder();
        WriteCSVRow(result, listView.Columns.Count, i => includeHidden || listView.Columns[i].Width > 0, i => listView.Columns[i].Text);

        //export data rows
        foreach (var listItem in listView.Items)
            WriteCSVRow(result, listView.Columns.Count, i => includeHidden || listView.Columns[i].Width > 0, i => listItem.SubItems[i].Text);

        File.WriteAllText(filePath, result.ToString());
    }

    private void WriteCSVRow(StringBuilder result, int itemsCount, Func<int, bool> isColumnNeeded, Func<int, string> columnValue)
    {
        bool isFirstTime = true;
        for (int i = 0; i < itemsCount; i++)
        {
            if (!isColumnNeeded(i))
                continue;

            if (!isFirstTime)
                result.Append(",");
            isFirstTime = false;

            result.Append(String.Format("\"{0}\"", columnValue(i)));
        }
        result.AppendLine();
    }
}
Yacoder
Showoff........
Robert Harvey
C'mon, maaan, upvote! :)))
Yacoder
That wasn't the deal. :) Does it work?
Robert Harvey
Sure. Why not??
Yacoder
+1 for a surprisingly elegant solution. ;)
Robert Harvey
Nice answer. One issue I've just found is that if the first column of your listview is an uppercase "ID", then excel refuses to open the CSV file without generating an error, as it stupidly thinks the file is an SYLK file. The best workaround I've found to prevent this happening is to simply convert the headers to lowercase. MS state you can put an apostrophe as the first character on the first line to fix this, but then you get an ugly apostrophe show up in excel. More info: http://support.microsoft.com/kb/215591
Bryan