NPOI讀取excel表,若是有公式取出的是公式,想要取數字怎麼辦?

 public static DataTable Import(string strFileName)
        {
            DataTable dt = new DataTable();

            HSSFWorkbook hssfworkbook;
            using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
            {
                hssfworkbook = new HSSFWorkbook(file);
            }
            ISheet sheet = hssfworkbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            IRow headerRow = sheet.GetRow(0);
            int cellCount = headerRow.LastCellNum;

            for (int j = 0; j < cellCount; j++)
            {
                ICell cell = headerRow.GetCell(j);
                dt.Columns.Add(cell.ToString());
            }

            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                DataRow dataRow = dt.NewRow();

                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                    {
                        //若是是公式Cell 
                        //則僅讀取其Cell單元格的顯示值 而不是讀取公式
                        if (row.GetCell(j).CellType == CellType.Formula)
                        {
                            row.GetCell(j).SetCellType(CellType.String);
                            dataRow[j] = row.GetCell(j).StringCellValue;
                        }
                        else
                        {
                            dataRow[j] = row.GetCell(j).ToString();
                        }
                    }
                }
                dt.Rows.Add(dataRow);
            }
            return dt;
        }
將單元格的類型轉換成numberic,
CellType.String  ,我在網上找的東西粘貼過來發現不過,找了半天緣由是大小寫的錯誤,
這裏是個枚舉,f12跟過去就能夠看見了,改爲相應的類型就OK
相關文章
相關標籤/搜索