Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...