C# 如何在 WPF 中将 ListView 导出为 .CSV?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15564297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:14:33 来源:igfitidea点击:
C# How can I export a ListView to .CSV in WPF?
提问by Jesson
How can I export a ListView (populated with sqlite) to .CSV in WPF? i can do it on winforms but not in wpf.. pls help. thanks in advance.
如何在 WPF 中将 ListView(填充有 sqlite)导出到 .CSV?我可以在 winforms 上做,但不能在 wpf 上做。请帮忙。提前致谢。


回答by Erwin
Convert ListView to Datatable:
将 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());
}
Use following code to make a csv:
使用以下代码制作 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();
}

