I need export ListView to csv and i found solution from this answer.Here
The problem is that I am getting full line into one column.
Code below:
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();
}
Any ideas what I have to do ?
This has nothing to do with CSVs. The first screenshot shows a perfectly good CSV. It also shows an attempt to open that file in Excel.
Excel will use the end-user's locale to decide what column, decimal separators and date formats to use. When you double-click on a text file Excel will import that data using the end-user's locale settings as the default.
In most European countries ,
is the decimal separator so it can't be used as a list separator too. Otherwise you wouldn't know what 100,00,234
mean. Is that 2 or 3 columns?
In such cases, the typical list separator is ;
. This is specified in the end user's locale settings. In most European countries you'd see 100,00;234
If you want your end users to be able to open the generated files in Excel with double-clicking you'll have to use the list and decimal separators that match their locales.
A better option would be to generate real Excel files with, eg Epplus. It doesn't require installing Excel on the client or server, and generates real Excel (xlsx) files.
Exporting your data can be as easy as a call to :
using (var pck = new ExcelPackage())
{
var sheet = pck.Workbook.Worksheets.Add("sheet");
sheet.Cells["C1"].LoadFromCollection(items);
pck.SaveAs(new FileInfo(@"c:\workbooks\myworkbook.xlsx"));
}