C#读取Excel数据丢失的问题处理方案

如excel有A,B两列,其A列的是标题,B列是内容且数据较多有字符数字符号等。那么直接读取B列会出现 B列数据不全的问题,网上找了各种方式设置还是不行,但是把excel转为.CSV格式读取  列数据就不会丢失了

读取CSV代码如下:

 string filePath = @"D:\测试\abc.csv";
public static DataTable ToCsv(string filePath) { //实例化一个datatable用来存储数据 DataTable dt = new DataTable(); //文件流读取 using (System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open)) { using (System.IO.StreamReader sr = new System.IO.StreamReader(fs, Encoding.GetEncoding("gb2312"))) { string tempText = ""; bool isFirst = true; while ((tempText = sr.ReadLine()) != null) { string[] arr = tempText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); //一般第一行为标题,所以取出来作为标头 if (isFirst) { foreach (string str in arr) { dt.Columns.Add(str); } isFirst = false; } else { //从第二行开始添加到datatable数据行 DataRow dr = dt.NewRow(); for (int i = 0; i < dt.Columns.Count; i++) { dr[i] = i < arr.Length ? arr[i] : ""; } dt.Rows.Add(dr); } } return dt; } } }

 

posted @ 2022-06-15 10:13  黑默丁格  阅读(283)  评论(0编辑  收藏  举报