NPOI读取excel表,如果有公式取出的是公式,想要取数字怎么办?

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
posted @ 2019-05-31 22:26  grj001  阅读(217)  评论(0编辑  收藏  举报