我有一个MVC控制器应该从string[][]
返回一个CSV文件。我正在尝试这个例子:
public FileContentResult DownloadCSV()
{
string[][] output = new string[][]{
new string[]{"Col 1 Row 1", "Col 2 Row 1", "Col 3 Row 1"},
new string[]{"Col1 Row 2", "Col2 Row 2", "Col3 Row 2"}
};
return File(output, "text/csv", "Report123.csv");
}
但我不知道如何创建文件。如何从string[][]
创建CSV文件?
答案 0 :(得分:2)
以下是使用LINQ的示例。
public FileContentResult DownloadCSV()
{
string[][] output = new string[][]{
new string[]{"Col 1 Row 1", "Col 2 Row 1", "Col 3 Row 1"},
new string[]{"Col1 Row 2", "Col2 Row 2", "Col3 Row 2"}
};
var result = lines.Select(l=>string.Join(",", l))
.Aggregate(new StringBuilder(), (sb, v) => sb.AppendLine(v))
.ToString();
return File(result, "text/csv", "Report123.csv");
}
......作为一种推广方法......
public static class ToolsEx
{
public static string ToCsvString(this string[][] lines)
{
var query = lines.Select(l=>string.Join(",", l));
var result = query.Aggregate(new StringBuilder(), (sb, v) => sb.AppendLine(v));
return result.ToString();
}
}
...在记住string.Join
使用StringBuilder内部之后,你可以将其进一步减少到(如果其他人想要在你之后保持这个,这可能会有点多)...
public static string ToCsvString(this string[][] rows)
{
return string.Join(Environment.NewLine, rows.Select(row => string.Join(",", row)));
}
答案 1 :(得分:1)
使用扩展方法生成csv文件
/// <summary>
/// Convert an array to string list, of the form "1,2,3,.."
/// </summary>
/// <param name="array">The array of numbers</param>
/// <returns>A string value</returns>
public static string ToCSVRow<T>(this T[] array)
{
string[] parts=new string[array.Length];
for(int i=0; i<parts.Length; i++)
{
parts[i]=array[i].ToString();
}
return string.Join(",", parts);
}
/// <summary>
/// Convert a jagged array to csv table, where each row has the form "1,2,3,.."
/// </summary>
/// <param name="array">The array of numbers</param>
/// <returns>A string value</returns>
public static string ToCSV<T>(this T[][] array)
{
List<string> csv=new List<string>();
for(int i=0; i<array.Length; i++)
{
csv.Add(array[i].ToCSVRow());
}
return string.Join(Environment.NewLine, csv.ToArray());
}
并与
一起使用return File(output.ToCSV(), "text/csv", "Report123.csv");
修改1
根据评论,执行以下操作会更简单,也许更快:
/// <summary>
/// Convert an array to a csv row, of the form "1,2,3,4.."
/// </summary>
/// <typeparam name="T">The array type</typeparam>
/// <param name="list">The array</param>
/// <returns>A comma delimited string</returns>
public static string ToCSVRow<T>(this T[] list)
{
return string.Join(",", list);
}
/// <summary>
/// Convert a jagged array to csv table, where each row has the form "1,2,3,.."
/// </summary>
/// <param name="array">The array of numbers</param>
/// <returns>A string value</returns>
public static string ToCSV<T>(this T[][] array)
{
return string.Join(Environment.NewLine, array.Select((row) => string.Join(",", row)));
}