Is anyone aware of a decent CSV export tool for exporting from a ListView? I'm in a mad rush to get a project update out and feature creep means I don't have time to get this final urgent feature implemented myself.
+2
A:
FileHelpers is a nice library that might just be your best friend today
second
2009-06-17 18:28:44
+8
A:
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 srting
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 (var 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 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();
}
}
Yacoder
2009-06-17 19:10:44
Showoff........
Robert Harvey
2009-06-17 19:17:18
C'mon, maaan, upvote! :)))
Yacoder
2009-06-17 19:21:24
That wasn't the deal. :) Does it work?
Robert Harvey
2009-06-17 19:24:30
Sure. Why not??
Yacoder
2009-06-17 19:28:28
+1 for a surprisingly elegant solution. ;)
Robert Harvey
2009-06-17 19:35:13
Nice answer. One issue I've just found is that if the first column of your listview is an uppercase "ID", then excel refuses to open the CSV file without generating an error, as it stupidly thinks the file is an SYLK file. The best workaround I've found to prevent this happening is to simply convert the headers to lowercase. MS state you can put an apostrophe as the first character on the first line to fix this, but then you get an ugly apostrophe show up in excel. More info: http://support.microsoft.com/kb/215591
Bryan
2009-08-29 10:19:11