在###中读取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. 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.

现在,我有时会把excel中的值显示为###,因为列空间不够大,无法显示数字。当然,在excel中,当我点击单元格时,我可以在上面的一行中看到正确的值,但是在我的程序中,我将### #作为值而不是正确的数字。

Any advice here?

任何建议吗?

3 个解决方案

#1


4  

Try using Range.Value property instead of Text.

尝试使用范围。值属性而不是文本。

So instead of

而不是

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

you would write

你会写

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

#2


1  

I have seen numerous examples where the Range is read using the property Value OR Value2.
Could you try this?

我已经看到了大量使用属性值或Value2读取范围的示例。你可以试试这个吗?

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. See here for an article on differences between Value and Value2

Value2属性与Value类似,但不能很好地转换日期列,因此如果您的Excel文件中有日期列,最好使用该值。这里有一篇关于Value和Value2之间差异的文章

#3


0  

use (string) (range.Cells[rCnt, cCnt] as Range).Value as Value will return the actual value of a cell. Text will return what you actually see on the spreadsheet

使用(字符串)(范围。细胞(rCnt cCnt]范围)。值作为值将返回单元格的实际值。文本将返回您在电子表格中看到的内容


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/04/25/b02e2ad3b999cf494ef09baf8b001e70.html



 
  © 2014-2022 ITdaan.com 联系我们: