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 @   黑默丁格  阅读(302)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示