I have a standalone c# App with a listview that display data read by my program. I am saving it as an excel file it works great , but the data when saved is dumped all in column, I have tried saving it as csv file ,but I cant get it to do what I want let each distinct be on a separate column please any heads up would highly welcome This is how my output is designed and I want that each should be on a separate column when I open the excel file.
listView1.Items.Add(vis.brand+ "," + (vis.Count) + ","vis.model + "," + Math.Round(vis.sum));
You could use this example, choose the C# version.
It should do exactly what you want to achieve. This function should do the trick:
private void Button1_Click(object sender, EventArgs e)
{
//declare new SaveFileDialog + set it's initial properties
SaveFileDialog sfd = new SaveFileDialog {
Title = "Choose file to save to",
FileName = "example.csv",
Filter = "CSV (*.csv)|*.csv",
FilterIndex = 0,
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
//show the dialog + display the results in a msgbox unless cancelled
if (sfd.ShowDialog() == DialogResult.OK) {
string[] headers = ListView1.Columns
.OfType<ColumnHeader>()
.Select(header => header.Text.Trim())
.ToArray();
string[][] items = ListView1.Items
.OfType<ListViewItem>()
.Select(lvi => lvi.SubItems
.OfType<ListViewItem.ListViewSubItem>()
.Select(si => si.Text).ToArray()).ToArray();
string table = string.Join(",", headers) + Environment.NewLine;
foreach (string[] a in items)
{
//a = a_loopVariable;
table += string.Join(",", a) + Environment.NewLine;
}
table = table.TrimEnd('\r', '\n');
System.IO.File.WriteAllText(sfd.FileName, table);
}
}
The answer by @McRonald mostly covers it, but will fail for important edge cases.
If you have a comma or quote in any string, it will mess up the output. For example if you had a CSV with columns LastName and FirstName, someone with a suffix like ", Jr" would throw off the commas:
LastName, FirstName
Smith, John
Baker, Jr, Fred
I developed an extension method that applies any necessary escaping to a string that is being written to a cell of a CSV file (the code could be shortened, but is easiest to follow as written):
static public class CsvExtensions
{
static public string CsvQuote(this string text)
{
if (text == null)
{
return string.Empty;
}
bool containsQuote = false;
bool containsComma = false;
bool containsNewline = false;
bool containsCR = false;
int len = text.Length;
for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
{
char ch = text[i];
if (ch == '"')
{
containsQuote = true;
}
else if (ch == ',')
{
containsComma = true;
}
else if (ch == '\r')
{
containsCR = true;
}
else if (ch == '\n')
{
containsNewline = true;
}
}
bool mustQuote = containsComma || containsQuote || containsCR || containsNewline;
if (containsQuote)
{
text = text.Replace("\"", "\"\"");
}
if (mustQuote)
{
return "\"" + text + "\""; // Quote the cell and replace embedded quotes with double-quote
}
else
{
return text;
}
}
}
You would place all of that code in it's own class, then use it like this (taking a line of code from @McRonald's answer):
table += string.Join(",", a) + Environment.NewLine;
becomes
table += string.Join(",", a.CsvQuote()) + Environment.NewLine;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.