2

我正在使用 NPOI 从 Excel 2003 文件中读取数据。这些文件包含像这样的公式SUM('1:2'!$C$17)。NPOI 识别此类公式,例如SUM('1'!$C$17)(不带表 2)并评估无效结果。我正在使用 NPOI 示例中的常规代码,例如

    foreach (var row in docRows)
            {
                sb.AppendFormat("{0}\t", SomeCode);
                rowCounter += 1;
                sb.AppendFormat("{0}\t", rowCounter);
                foreach (var col in docColumns)
                {
                    ICell cell = sheet.GetRow(row).GetCell(col);

                    sb.AppendFormat("{0}\t", GetExcelCellValue(cell));
                }
                sb.AppendLine();
            }
private string GetExcelCellValue(ICell cell)
        {
            string cellValue = string.Empty;
            IFormulaEvaluator evaluator = _hssfworkbook.GetCreationHelper().CreateFormulaEvaluator();
            evaluator.Evaluate(cell);

            switch (evaluator.EvaluateInCell(cell).CellType)
            {
                case CellType.BLANK:
                    cellValue = string.Empty;
                    break;
                case CellType.BOOLEAN:
                    cellValue = string.Empty;
                    break;
                case CellType.NUMERIC:
                    cellValue = Convert.ToString(cell.NumericCellValue);    //This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number.
                    break;
                case CellType.STRING:
                    throw new ArgumentNullException();
                    cellValue = cell.StringCellValue;
                    break;
                case CellType.ERROR:
                    cellValue = string.Empty;
                    break;
                case CellType.FORMULA:

                    break;

            }
            return cellValue;
        }
4

1 回答 1

0

我刚刚遇到这个问题,我解决了

switch (cell.CellType)
                {
                    case CellType.Blank:
                        cellValue = "";
                        break;
                    case CellType.Boolean:
                        cellValue = cell.BooleanCellValue.ToString();
                        break;
                    case CellType.Formula:

                        cellValue = cell.NumericCellValue.ToString();
                        break;
                    case CellType.Numeric:
                        cellValue = cell.NumericCellValue.ToString();
                        break;
                    case CellType.String:
                        cellValue = cell.StringCellValue;
                        break;
                }
于 2017-05-26T12:54:03.793 回答