简体   繁体   中英

Export ListView to CSV

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

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 string
        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 (ListViewItem 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 static 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();
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM