Excel To Dataset 解决读取丢失数据

来源:互联网 发布:淘宝违规用手机怎么查 编辑:程序博客网 时间:2024/05/17 05:51

这几天做的一个项目,遇到excel数据导入的问题,例excel中有一列“软件版本号”,数据格式为,

2.2

2.1

2.36

2.3.6.3

2.3.6.88/2.3.23/4.3

 

 

一行,当用读取到dataset时,dataset中最后二行的数据为空了,这时dataset的表中这列的数据类型为double

 

问题大概是这样。

解决方法,直接上代码更好

 public static DataSet ExcelToDataSet(string strFilePath)
    {
        string strConn;
        strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
        OleDbConnection conn = new OleDbConnection(strConn);
        conn.Open();
        DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });//获得Excel中的所有sheetname
        OleDbDataAdapter odda;
        DataSet ds = new DataSet();
        foreach (DataRow dr in sheetNames.Rows)
        {
            DataSet dsOne = new DataSet();
            odda = new OleDbDataAdapter("select * from [" + dr[2] + "]", strConn);//dr[2] is sheetname
            odda.Fill(dsOne);
          
            if (dsOne.Tables.Count > 0)
            {
                DataTable dt = dsOne.Tables[0].Copy();
                dt.TableName = dr[2].ToString();
                ds.Tables.Add(dt);
            }
        }
        conn.Close();
        return ds;
    }

,然后excel中对应列的第一行数据的单元格,双击,把光标移到最前,输入”'“,把这列的数据类型强制转换为字符类型,注意strConn 中加粗部分,开始做项目时没有加入,导致这个问题存在。

  "HDR=Yes;"   indicates   that   the   first   row   contains   columnnames,   not   data  
  "IMEX=1;"   tells   the   driver   to   always   read   "intermixed"   data   columns   as   text  

这个解释从csdn搜出来的,这里做总结,以备以后参考,希望有用。