2

如何在 WPF 中将 ListView(填充有 sqlite)导出到 .CSV?我可以在winforms上做到这一点,但不能在wpf中做到这一点。请帮忙。提前致谢。

在此处输入图像描述

4

1 回答 1

6

将 ListView 转换为数据表:

var listView1 = new ListView();
DataTable table = new DataTable();
foreach (ListViewItem item in listView1.Items)
{
    table.Columns.Add(item.ToString());
    foreach (var it in item.SubItems)
         table.Rows.Add(it.ToString());
 }

使用以下代码制作 csv:

public void CreateCSVFile(DataTable dt, string strFilePath)
{
    StreamWriter sw = new StreamWriter(strFilePath, false);

    int iColCount = dt.Columns.Count;
    for (int i = 0; i < iColCount; i++)
    {
        sw.Write(dt.Columns[i]);
        if (i < iColCount - 1)
        {
            sw.Write(",");
        }
    }
    sw.Write(sw.NewLine);

    foreach (DataRow dr in dt.Rows)
    {
        for (int i = 0; i < iColCount; i++)
        {
            if (!Convert.IsDBNull(dr[i]))
            {
                sw.Write(dr[i].ToString());
            }
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);
    }
    sw.Close();
}
于 2013-03-22T07:10:50.957 回答