将DataTable转换成CSV文件是一种常见的转换形式,主要通过遍历Table的每行,再对每行遍历每列,实现对数据的读取,然后用分隔符分隔Table的每个栏位数据,把读取的字符写入到CSV文件中。这里每个栏位之间用逗号分隔,每行用换行符。实现代码如下:
public ExecutionResult DataTableToCsv(System.Data.DataTable vContent, string vOutputFilePath) { ExecutionResult sResult = new ExecutionResult(); System.Text.StringBuilder sCsvContent; try { sCsvContent = new System.Text.StringBuilder(); //栏位 for (int i = 0; i < vContent.Columns.Count; i++) { sCsvContent.Append(vContent.Columns[i].ColumnName); sCsvContent.Append(i == vContent.Columns.Count - 1 ? "\r\n" : ","); } //数据 foreach (System.Data.DataRow row in vContent.Rows) { for (int i = 0; i < vContent.Columns.Count; i++) { sCsvContent.Append(row[i].ToString().Trim()); sCsvContent.Append(i == vContent.Columns.Count - 1 ? "\r\n" : ","); } } File.WriteAllText(vOutputFilePath, sCsvContent.ToString(), Encoding.UTF8); sResult.Status = true; } catch (Exception ex) { sResult.Message = ex.Message; sResult.Status = false; } return sResult; }