以下代码将结果输出到csv文件。假设'valueDataList'中有10个值...当运行它时,只有一行输出到该文件。如何循环代码以在“valueDataList”中“一次”打印所有值的文件。
foreach (var value in valueDataList)
{
var value1 = xxxxxxx // this value is set here based on a query..
int value2 = xxxxxxxx // this value is set here based on a query..
byte[] content;
using (var ms = new MemoryStream())
{
using (var writer = new StreamWriter(ms))
{
writer.WriteLine("ValueHeading1 " + " ValueHeading2");
writer.WriteLine(value1 + " " + value2);
}
content = ms.ToArray();
return File(content, "text/csv", "demo.csv");
}
}
基本上我希望能够在每次循环迭代时追加到现有的csv文件。我怎样才能做到这一点?谢谢你的帮助。
答案 0 :(得分:1)
你的意思是你想要将valueDataList中的所有行写入csv文件吗? 如果是的话;
using (var ms = new MemoryStream())
using (var writer = new StreamWriter(ms))
{
writer.WriteLine("ValueHeading1 " + " ValueHeading2");
foreach (var value in valueDataList)
{
var value1 = xxxxxxx // this value is set here based on a query..
int value2 = xxxxxxxx // this value is set here based on a query..
writer.WriteLine(value1 + " " + value2);
}
byte[] content = ms.ToArray();
return File(content, "text/csv", "demo.csv");
}
答案 1 :(得分:0)