Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
378 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...