OleDB & mixed Excel datatypes : missing data

后端 未结 6 1081
长发绾君心
长发绾君心 2020-11-22 03:04

I have an Excel worksheet I want to read into a datatable - all is well except for one particular column in my Excel sheet. The column, \'ProductID\', is a mix of values lik

6条回答
  •  借酒劲吻你
    2020-11-22 03:57

    Several forums I found claim that by adding IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text to the Extended Properties in the connection string would fix the problem, but this was not the case. I finally solved this problem by adding "HDR=NO" to the Extended Properties in the connection string (as Brian Wells shows above) so that I could import mixed types.

    I then added some generic code to name the columns after the first row of data, then remove the first row.

        public static DataTable ImportMyDataTableFromExcel(string filePath)
        {
            DataTable dt = new DataTable();
    
            string fullPath = Path.GetFullPath(filePath);
    
            string connString =
               "Provider=Microsoft.Jet.OLEDB.4.0;" +
               "Data Source=\"" + fullPath + "\";" +
               "Extended Properties=\"Excel 8.0;HDR=No;IMEX=1;\"";
    
            string sql = @"SELECT * FROM [sheet1$]";
    
            using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, connString))
            {
                dataAdapter.Fill(dt);
            }
    
            dt = BuildHeadersFromFirstRowThenRemoveFirstRow(dt);
    
            return dt;
        }
    
        private static DataTable BuildHeadersFromFirstRowThenRemoveFirstRow(DataTable dt)
        {
            DataRow firstRow = dt.Rows[0];
    
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                if(!string.IsNullOrWhiteSpace(firstRow[i].ToString())) // handle empty cell
                  dt.Columns[i].ColumnName = firstRow[i].ToString().Trim();
            }
    
            dt.Rows.RemoveAt(0);
    
            return dt;
        }
    

提交回复
热议问题