[英]Saving contents of listview as a CSV File in c#
我有一个带有列表视图的独立c#应用程序,它显示程序读取的数据。 我将其保存为一个效果很好的excel文件,但是保存时的数据将全部转储到列中,我尝试将其保存为csv文件,但是我无法做到这一点,我希望每个不同的对象都放在单独的列中请大家注意,这是我的输出的设计方式,我希望当我打开excel文件时,每个输出都放在单独的列中。
listView1.Items.Add(vis.brand+ "," + (vis.Count) + ","vis.model + "," + Math.Round(vis.sum));
您可以使用此示例,选择C#版本。
它应该正是您想要实现的目标。 这个函数应该可以解决问题:
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);
}
}
@McRonald的答案基本上可以解决这个问题,但是在重要的情况下将失败。
如果任何字符串中都有逗号或引号,则会使输出混乱。 例如,如果您有一个具有LastName和FirstName列的CSV,则后缀为“,Jr”的人会抛出逗号:
LastName, FirstName
Smith, John
Baker, Jr, Fred
我开发了一种扩展方法,该方法将任何必要的转义应用于正在写入CSV文件单元格的字符串(该代码可以缩短,但是按照编写的方式最容易遵循):
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;
}
}
}
您可以将所有代码放在自己的类中,然后像这样使用它(从@McRonald的答案中提取一行代码):
table += string.Join(",", a) + Environment.NewLine;
变
table += string.Join(",", a.CsvQuote()) + Environment.NewLine;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.