CsvHelper.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Data;
  2. using System.IO;
  3. namespace Ant.Service.Utilities
  4. {
  5. /// <summary>
  6. /// CSV文件转换类
  7. /// </summary>
  8. public static class CsvHelper
  9. {
  10. /// <summary>
  11. /// 导出报表为Csv
  12. /// </summary>
  13. /// <param name="dt">DataTable</param>
  14. /// <param name="strFilePath">物理路径</param>
  15. /// <param name="tableheader">表头</param>
  16. /// <param name="columname">字段标题,逗号分隔</param>
  17. public static bool dt2csv(DataTable dt, string strFilePath, string tableheader, string columname)
  18. {
  19. try
  20. {
  21. string strBufferLine = "";
  22. StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8);
  23. strmWriterObj.WriteLine(tableheader);
  24. strmWriterObj.WriteLine(columname);
  25. for (int i = 0; i < dt.Rows.Count; i++)
  26. {
  27. strBufferLine = "";
  28. for (int j = 0; j < dt.Columns.Count; j++)
  29. {
  30. if (j > 0)
  31. strBufferLine += ",";
  32. strBufferLine += dt.Rows[i][j].ToString();
  33. }
  34. strmWriterObj.WriteLine(strBufferLine);
  35. }
  36. strmWriterObj.Close();
  37. return true;
  38. }
  39. catch
  40. {
  41. return false;
  42. }
  43. }
  44. /// <summary>
  45. /// 将Csv读入DataTable
  46. /// </summary>
  47. /// <param name="filePath">csv文件路径</param>
  48. /// <param name="n">表示第n行是字段title,第n+1行是记录开始</param>
  49. public static DataTable csv2dt(string filePath, int n, DataTable dt)
  50. {
  51. StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8, false);
  52. int i = 0, m = 0;
  53. reader.Peek();
  54. while (reader.Peek() > 0)
  55. {
  56. m = m + 1;
  57. string str = reader.ReadLine();
  58. if (m >= n + 1)
  59. {
  60. string[] split = str.Split(',');
  61. System.Data.DataRow dr = dt.NewRow();
  62. for (i = 0; i < split.Length; i++)
  63. {
  64. dr[i] = split[i];
  65. }
  66. dt.Rows.Add(dr);
  67. }
  68. }
  69. return dt;
  70. }
  71. }
  72. }