如何从List< String []>创建CSV文件 [英] How to create a csv file from List<String[]>
问题描述
谁能帮我从List创建一个csv文件,我的情况是,我在List中有一个像下面这样的多维值
Can anyone help me to create a csv file from List, my scenario is, i have a multi dimensional values like below in a List
List<string[]> lst = new List<string[]>();
lst= csv1.ToList();
lst包含类似的值,
lst contains the values like,
lst[0] = {string[53]}
lst[1] = {string[53]}
lst[2] = {string[53]}
lst[3] = {string[53]}
lst[4] = {string[53]}
和字符串[53]包含类似
and string[53] contains the values like
lst[0]
string[0] = "abc"
string[1] = "def"
string[2] = "ghi"
string[3] = "jkl"
string[4] = "mno"
...
lst[1]
string[0] = "123"
string[1] = "456"
string[2] = "789"
string[3] = "10"
string[4] = "11"
...
我只是想将此多维列表写到csv文件中,因为lst []中的每个项目都写到csv中的行中,而string []中的每个项目写到列中,这样我的csv中的最终输出是
I just wanted to write this multi-dimensional list to csv file as each item in lst[] to rows in csv and each item in string[] to columns such that the final output in my csv is
abc,def,ghi,jkl,mno
123,456,789,10,11
任何帮助将不胜感激.
推荐答案
在最简单的级别上,不处理引号/转义/多行CSV问题,然后循环即可;也许是这样的:
At the simplest level, not handling quoting / escaping / multi-line CSV issues, then just loop; maybe something like:
using (var file = File.CreateText(path))
{
foreach(var arr in lst)
{
file.WriteLine(string.Join(",", arr));
}
}
或 tiny 效率更高(无中间字符串):
or a tiny bit more efficient (no intermediary string):
using (var file = File.CreateText(path))
{
foreach (var arr in lst)
{
if (String.IsNullOrEmpty(arr)) continue;
file.Write(arr[0]);
for(int i = 1 ; i < arr.Length ; i++)
{
file.Write(',');
file.Write(arr[i]);
}
file.WriteLine();
}
}
这篇关于如何从List< String []>创建CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!