Accessing Excel Spreadsheet with C# occasionally returns blank value for some cells

后端 未结 10 2122
無奈伤痛
無奈伤痛 2020-12-11 02:43

I need to access an excel spreadsheet and insert the data from the spreadsheet into a SQL Database. However the Primary Keys are mixed, most are numeric and some are alpha-n

相关标签:
10条回答
  • 2020-12-11 03:03

    For VISTA compatibility you can use EXCEL 12.0 driver in connection string. This should resolve your issue. It did mine.

    0 讨论(0)
  • 2020-12-11 03:04

    hi all this code is gets alphanumeric values also

    using System.Data.OleDb;
    
    string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filepath + ";" + "Extended Properties="+(char)34+"Excel 8.0;IMEX=1;"+(char)34;
    
    string CommandText = "select * from [Sheet1$]";
    
    OleDbConnection myConnection = new OleDbConnection(ConnectionString);
    myConnection.Open();
    
    OleDbDataAdapter myAdapter = new OleDbDataAdapter(CommandText, myConnection);
    
    ds = null;
    ds = new DataSet();
    myAdapter.Fill(ds);
    
    0 讨论(0)
  • 2020-12-11 03:05

    The Excel data source picks a column type for the entire column. If one of the cells doesn't match that type exactly, it leaves blanks like that. We had issues where our typist entered a " 8" (a space before the number, so Excel converted it to a string for that cell) in a numeric column. It would make sense to me that it would try the .Net Parse methods as they are more robust, but I guess that's not how the Excel driver works.

    Our fix, since we were using database import services, was to log all the rows that 'failed' this way. Then, we went back to the XLS document and re-typed those cells, to ensure the underlying type was correct. (We found just deleting the space didn't fix it--we had to Clear the whole cell first, than re-type the '8'.) Feels hacky and isn't elagent, but that was the best method we found. If the Excel driver can't read it in correctly by itself, there's nothing you can do to get that data out of there once you're in .Net.

    Just another case where Office hides the important details from users in the name of simplicity, and therefore making it more difficult when you have to be exact for power uses.

    0 讨论(0)
  • 2020-12-11 03:08

    The {} means this is some sort of empty object and not a string. When you hover over the object you should be able to see its type. Likewise, when you use quickwatch to view dr["..."] you should see the object type. What type is the object you receive?

    0 讨论(0)
提交回复
热议问题