在 c# 中将列表视图的内容另存为 CSV 文件
本文关键字:另存为 CSV 文件 视图 列表 | 更新日期: 2023-09-27 18:36:34
我有一个独立的 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的答案主要涵盖它,但对于重要的边缘情况会失败。
如果任何字符串中有逗号或引号,则会弄乱输出。 例如,如果您有一个包含"姓氏"和"名字"列的 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;