简体   繁体   English

C#从excel文件读取数据导致###

[英]C# read data from excel file results in ###

i read data from an excel file with this code 我用这段代码从excel文件中读取数据

        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        Microsoft.Office.Interop.Excel.Range range;

        int rCnt = 0;
        int cCnt = 0;
        string[,] data;

        xlWorkSheet = (Worksheet)wb.Worksheets.get_Item(sheetId);

        range = xlWorkSheet.UsedRange;

        data = new string[range.Rows.Count, range.Columns.Count];

        for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
        {
            for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
            {          
                data[rCnt - 1, cCnt - 1] = (string)
                (range.Cells[rCnt, cCnt] as Range).Text;
            }
        }

Now i am running sometimes into cells where the value in excel is displayed as ### because the column space is not big enough to display the number. 现在我有时会进入单元格,其中excel中的值显示为###,因为列空间不足以显示数字。 In excel of course i can see the right value in the line on the top when i click on the cell but in my program i am getting the ### as value instead of the right number. 当然,当我点击单元格时,我可以在顶部的行中看到正确的值,但在我的程序中,我得到###作为值而不是正确的数字。

Any advice here? 有什么建议吗?

Try using Range.Value property instead of Text . 尝试使用Range.Value属性而不是Text

So instead of 而不是

(range.Cells[rCnt, cCnt] as Range).Text;

you would write 你会写的

(range.Cells[rCnt, cCnt] as Range).Value;

I have seen numerous examples where the Range is read using the property Value OR Value2. 我已经看过很多使用属性Value OR Value2读取Range的示例。
Could you try this? 你能试试吗?

data[rCnt - 1, cCnt - 1] = (string)(range.Cells[rCnt, cCnt] as Range).Value.ToString();

The Value2 property is similar to Value but don't translate well the Date columns, so it's better to use the Value if you have date columns in your Excel File. Value2属性与Value类似,但不能很好地翻译Date列,因此如果Excel文件中有日期列,最好使用Value。 See here for an article on differences between Value and Value2 请参阅此处,了解有关Value和Value2之间差异的文章

use (string) (range.Cells[rCnt, cCnt] as Range).Value as Value will return the actual value of a cell. use(string)(range.Cells [rCnt,cCnt] as Range)。ValueValue将返回一个单元格的实际值。 Text will return what you actually see on the spreadsheet 文本将返回您在电子表格中实际看到的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM