请选择 进入手机版 | 继续访问电脑版

Hello Mat

 找回密码
 立即注册
查看: 7612|回复: 0

C#读取、写入CSV文件

[复制链接]

1278

主题

1504

帖子

90

金钱

管理员

Rank: 9Rank: 9Rank: 9

积分
22549
发表于 2017-11-14 22:42:51 | 显示全部楼层 |阅读模式
C#读取、写入CSV文件

读取CSV文件到DataTable,方便插入到界面datagridview中:
  1. public static DataTable OpenCSV(string filePath)//从csv读取数据返回table
  2. {
  3.     System.Text.Encoding encoding = GetType(filePath); //Encoding.ASCII;//
  4.     DataTable dt = new DataTable();
  5.     System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open,
  6.         System.IO.FileAccess.Read);

  7.     System.IO.StreamReader sr = new System.IO.StreamReader(fs, encoding);

  8.     //记录每次读取的一行记录
  9.     string strLine = "";
  10.     //记录每行记录中的各字段内容
  11.     string[] aryLine = null;
  12.     string[] tableHead = null;
  13.     //标示列数
  14.     int columnCount = 0;
  15.     //标示是否是读取的第一行
  16.     bool IsFirst = true;
  17.     //逐行读取CSV中的数据
  18.     while ((strLine = sr.ReadLine()) != null)
  19.     {
  20.         if (IsFirst == true)
  21.         {
  22.             tableHead = strLine.Split(',');
  23.             IsFirst = false;
  24.             columnCount = tableHead.Length;
  25.             //创建列
  26.             for (int i = 0; i < columnCount; i++)
  27.             {
  28.                 DataColumn dc = new DataColumn(tableHead[i]);
  29.                 dt.Columns.Add(dc);
  30.             }
  31.         }
  32.         else
  33.         {
  34.             aryLine = strLine.Split(',');
  35.             DataRow dr = dt.NewRow();
  36.             for (int j = 0; j < columnCount; j++)
  37.             {
  38.                 dr[j] = aryLine[j];
  39.             }
  40.             dt.Rows.Add(dr);
  41.         }
  42.     }
  43.     if (aryLine != null && aryLine.Length > 0)
  44.     {
  45.         dt.DefaultView.Sort = tableHead[0] + " " + "asc";
  46.     }

  47.     sr.Close();
  48.     fs.Close();
  49.     return dt;
  50. }
  51. /// 给定文件的路径,读取文件的二进制数据,判断文件的编码类型
  52. /// <param name="FILE_NAME">文件路径</param>
  53. /// <returns>文件的编码类型</returns>

  54. public static System.Text.Encoding GetType(string FILE_NAME)
  55. {
  56.     System.IO.FileStream fs = new System.IO.FileStream(FILE_NAME, System.IO.FileMode.Open,
  57.         System.IO.FileAccess.Read);
  58.     System.Text.Encoding r = GetType(fs);
  59.     fs.Close();
  60.     return r;
  61. }

  62. /// 通过给定的文件流,判断文件的编码类型
  63. /// <param name="fs">文件流</param>
  64. /// <returns>文件的编码类型</returns>
  65. public static System.Text.Encoding GetType(System.IO.FileStream fs)
  66. {
  67.     byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
  68.     byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
  69.     byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM
  70.     System.Text.Encoding reVal = System.Text.Encoding.Default;

  71.     System.IO.BinaryReader r = new System.IO.BinaryReader(fs, System.Text.Encoding.Default);
  72.     int i;
  73.     int.TryParse(fs.Length.ToString(), out i);
  74.     byte[] ss = r.ReadBytes(i);
  75.     if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
  76.     {
  77.         reVal = System.Text.Encoding.UTF8;
  78.     }
  79.     else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
  80.     {
  81.         reVal = System.Text.Encoding.BigEndianUnicode;
  82.     }
  83.     else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
  84.     {
  85.         reVal = System.Text.Encoding.Unicode;
  86.     }
  87.     r.Close();
  88.     return reVal;
  89. }

  90. /// 判断是否是不带 BOM 的 UTF8 格式
  91. /// <param name="data"></param>
  92. /// <returns></returns>
  93. private static bool IsUTF8Bytes(byte[] data)
  94. {
  95.     int charByteCounter = 1;  //计算当前正分析的字符应还有的字节数
  96.     byte curByte; //当前分析的字节.
  97.     for (int i = 0; i < data.Length; i++)
  98.     {
  99.         curByte = data[i];
  100.         if (charByteCounter == 1)
  101.         {
  102.             if (curByte >= 0x80)
  103.             {
  104.                 //判断当前
  105.                 while (((curByte <<= 1) & 0x80) != 0)
  106.                 {
  107.                     charByteCounter++;
  108.                 }
  109.                 //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X 
  110.                 if (charByteCounter == 1 || charByteCounter > 6)
  111.                 {
  112.                     return false;
  113.                 }
  114.             }
  115.         }
  116.         else
  117.         {
  118.             //若是UTF-8 此时第一位必须为1
  119.             if ((curByte & 0xC0) != 0x80)
  120.             {
  121.                 return false;
  122.             }
  123.             charByteCounter--;
  124.         }
  125.     }
  126.     if (charByteCounter > 1)
  127.     {
  128.         throw new Exception("非预期的byte格式");
  129.     }
  130.     return true;
  131. }
复制代码

在此特别注意输入的路径是string类型;注意:如果是其它软件转换的变量.tostring()也会有格式差异的。


参考:
【1】http://blog.csdn.net/xgf415/article/details/51366877

算法QQ  3283892722
群智能算法链接http://halcom.cn/forum.php?mod=forumdisplay&fid=73
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Python|Opencv|MATLAB|Halcom.cn ( 蜀ICP备16027072号 )

GMT+8, 2024-3-29 01:36 , Processed in 0.213304 second(s), 24 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表