Can I specify the data type for a column rather th

2019-07-29 18:06发布

问题:

I have noticed the following when working with linq-to-excel:

I'm trying to import rooms from a spreadsheet.

I have a simple class

   public class Room
    {
        public int BuildingID { get; set; }
        public string RoomNumber { get; set; }
        public double SQM { get; set; }
        public string Notes { get; set; }
    }

The room numbers in the spreadsheet are either simple numbers e.g. 101, 102, 34 etc or they have a character prefix e.g. AV1, LH2 etc

If the 1st row in my sheet starts with an alphanumeric room number (e.g. LH1), everything is fine and the RoomNumber column is treated as string data.

On another sheet, the first few rows are numeric. When my loop gets to the first alphanumeric room number, the class has a null instead of e.g. AV1 even though the rest of the row is there. It's almost like linq-to-excel has looked at the first few rows and decided that the column data type should be numeric.

Is there a way that I can force the string data type from my class?

回答1:

The issue has to do with the OLEDB provider which LinqToExcel uses.

Here's a stack overflow question that explains the issue: Excel cell-values are truncated by OLEDB-provider

The article explains that adding HDR=YES helps with the problem, and LinqToExcel already sets that property.

So basically you need to have an alphanumeric room number in the first 8 or 16 rows. Else OLEDB treats all the values in that column as numbers instead of strings.