C# 将 ListView 导出为 CSV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1008556/
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
Export ListView to CSV
提问by djdd87
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.
有没有人知道用于从 ListView 导出的不错的 CSV 导出工具?我需要进行项目更新,而功能蠕变意味着我没有时间自己实现这个最终功能。
采纳答案by Max Galkin
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();
}
}
回答by second
FileHelpersis a nice library that might just be your best friend today
FileHelpers是一个不错的库,它可能只是你今天最好的朋友