将Listview的内容导出为CSV文件

时间:2017-07-26 12:08:11

标签: c# csv listview export

我有5个列表视图,我想将其导出到一个CSV文件中。

This is my 5 listview

在列表视图中,您可以看到所有6个列表视图的日期时间相同。

所以我能够将第一个listview导出到CSV文件中。

        saveFileDialog1.Filter = "csv files (*.csv)|*.csv";
        saveFileDialog1.FileName = "logs";
        saveFileDialog1.Title = "Export to Excel";
        StringBuilder sb = new StringBuilder();
        foreach (ColumnHeader ch in listView1.Columns)
        {
            sb.Append(ch.Text + ",");
        }
        sb.AppendLine();
        foreach (ListViewItem lvi in listView1.Items)
        {
            foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
            {
                if (lvs.Text.Trim() == string.Empty)
                    sb.Append(" ,");
                else
                    sb.Append(lvs.Text + ",");
            }
            sb.AppendLine();
        }
        DialogResult dr = saveFileDialog1.ShowDialog();
        if (dr == DialogResult.OK)
        {
            StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);
            sw.Write(sb.ToString());
            sw.Close();

            this.Close();
        }

现在我想将剩下的其他4个listview导出到同一个CSV文件中,其中第一个colomn将是Date Time,这对于所有5个listview都是相同的。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

完成代码以完成任务

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