从字符串 [][] 生成 CSV 文件
本文关键字:文件 CSV 生成 字符串 | 更新日期: 2023-09-27 18:33:30
我有一个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 文件?
下面是
使用 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)));
}
使用扩展方法生成 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)));
}