我想从Dataset生成多个不同的.csv文件(里面有很多表)
我尝试过以下但不知道生成不同csv的代码。
public string GenerateCSVfiles(List<DataSet> dataSets)
{
//create csv file
foreach (DataRow row in dataTable.Rows)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
result.Append(row[i].ToString());
result.Append(i == dataTable.Columns.Count - 1 ? "\n" : ",");
}
}
return result.ToString();
}
//return Files in .zip;
}
答案 0 :(得分:4)
尝试此代码:使用数据名称生成csv文件名:
public void GenerateCSVfiles(DataSet dataSets)
{
//create csv file
StreamWriter sw = null;
StringBuilder sb = new StringBuilder();
foreach (DataTable dataTable in dataSets.Tables)
{
sw = new StreamWriter(string.Format(@"C:\Temp\{0}.csv", dataTable.TableName));
for (int i = 0; i < dataTable.Rows.Count; i++)
{
sb.Clear();
for (int j = 0; j < dataTable.Columns.Count; j++)
{
sb.Append(dataTable.Rows[i][j]);
if (j != (dataTable.Columns.Count - 1)) sb.Append(",");
}
sw.WriteLine(sb.ToString());
}
sw.Close();
}
}