在###中讀取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 联系我们: