Export ListView to CSV

Does anyone know of a decent CSV export tool for exporting from ListView? I am in a crazy rush to get the project updated, and the creep function means that I don’t have time to implement this last urgent function realized by me.

+3
source share
2 answers

This is not a big feature, which I would say if you do not have very strange requirements ... but in this case, perhaps, no external tool can help you.

This 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();
    }
}
+35
source
+2

Source: https://habr.com/ru/post/1710701/


All Articles