Exemplo n.º 1
0
 private Object getNumericCellValue(final Cell cell) {
   Object cellValue;
   if (DateUtil.isCellDateFormatted(cell)) {
     cellValue = new Date(cell.getDateCellValue().getTime());
   } else {
     cellValue = cell.getNumericCellValue();
   }
   return cellValue;
 }
  public Object getDataFromCell(final Cell cell) {

    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
      return cell.getNumericCellValue();
    } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
      return cell.getStringCellValue();
    }

    return null;
  }
  public void testModifyArrayCells_setCellFormula() {
    Workbook workbook = _testDataProvider.createWorkbook();
    Sheet sheet = workbook.createSheet();

    CellRange<? extends Cell> srange =
        sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5"));
    Cell scell = srange.getTopLeftCell();
    assertEquals("SUM(A4:A6,B4:B6)", scell.getCellFormula());
    assertEquals(Cell.CELL_TYPE_FORMULA, scell.getCellType());
    assertTrue(scell.isPartOfArrayFormulaGroup());
    scell.setCellFormula("SUM(A4,A6)");
    // we are now a normal formula cell
    assertEquals("SUM(A4,A6)", scell.getCellFormula());
    assertFalse(scell.isPartOfArrayFormulaGroup());
    assertEquals(Cell.CELL_TYPE_FORMULA, scell.getCellType());
    // check that setting formula result works
    assertEquals(0.0, scell.getNumericCellValue());
    scell.setCellValue(33.0);
    assertEquals(33.0, scell.getNumericCellValue());

    // multi-cell array formula
    CellRange<? extends Cell> mrange =
        sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3"));
    for (Cell mcell : mrange) {
      // we cannot set individual formulas for cells included in an array formula
      try {
        assertEquals("A1:A3*B1:B3", mcell.getCellFormula());
        mcell.setCellFormula("A1+A2");
        fail("expected exception");
      } catch (IllegalStateException e) {
        CellReference ref = new CellReference(mcell);
        String msg =
            "Cell "
                + ref.formatAsString()
                + " is part of a multi-cell array formula. You cannot change part of an array.";
        assertEquals(msg, e.getMessage());
      }
      // a failed invocation of Cell.setCellFormula leaves the cell
      // in the state that it was in prior to the invocation
      assertEquals("A1:A3*B1:B3", mcell.getCellFormula());
      assertTrue(mcell.isPartOfArrayFormulaGroup());
    }
  }
  private static InterviewInstance getInstance(Row row) throws ParseException {

    // extract the cells needed from this row
    Cell interview_id_cell = row.getCell(0, Row.CREATE_NULL_AS_BLANK);
    Cell line_cell = row.getCell(1, Row.CREATE_NULL_AS_BLANK);
    Cell speaker_cell = row.getCell(2, Row.CREATE_NULL_AS_BLANK);
    Cell comment_cell = row.getCell(3, Row.CREATE_NULL_AS_BLANK);
    ArrayList<Cell> category_cells = new ArrayList<>(5);
    for (int i = 4; i <= 8; ++i) {
      Cell cell = row.getCell(i, Row.CREATE_NULL_AS_BLANK);
      if (cell.getCellType() != Cell.CELL_TYPE_BLANK) category_cells.add(cell);
    }
    Cell sentiment_cell = row.getCell(9, Row.CREATE_NULL_AS_BLANK);

    // verify that all the required information is present
    verifyNumericCell(interview_id_cell, "Interview ID field");
    verifyNumericCell(line_cell, "Line field");
    verifySpeakerCell(speaker_cell);
    verifyCellNotEmpty(comment_cell, "Comment cell");

    if (category_cells.isEmpty())
      throw new ParseException("No category labels given for samples in row " + row.getRowNum(), 0);

    Iterator<Cell> row_iter = category_cells.iterator();
    ArrayList<Category> categories = new ArrayList<>();
    while (row_iter.hasNext()) {
      Cell category_cell = row_iter.next();
      verifyCategoryCell(category_cell);
      categories.add(Category.getCategory(category_cell.getStringCellValue()));
    }

    // convert the cell into an interviewInstance
    InterviewInstance instance =
        new InterviewInstance(
            (int) interview_id_cell.getNumericCellValue(),
            (int) line_cell.getNumericCellValue(),
            Speaker.getSpeaker(speaker_cell.getStringCellValue()),
            comment_cell.getStringCellValue(),
            categories);

    return instance;
  }
  /** Test that we can set pre-calculated formula result for array formulas */
  public void testModifyArrayCells_setFormulaResult() {
    Workbook workbook = _testDataProvider.createWorkbook();
    Sheet sheet = workbook.createSheet();

    // single-cell array formula
    CellRange<? extends Cell> srange =
        sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5"));
    Cell scell = srange.getTopLeftCell();
    assertEquals(Cell.CELL_TYPE_FORMULA, scell.getCellType());
    assertEquals(0.0, scell.getNumericCellValue());
    scell.setCellValue(1.1);
    assertEquals(1.1, scell.getNumericCellValue());

    // multi-cell array formula
    CellRange<? extends Cell> mrange =
        sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3"));
    for (Cell mcell : mrange) {
      assertEquals(Cell.CELL_TYPE_FORMULA, mcell.getCellType());
      assertEquals(0.0, mcell.getNumericCellValue());
      double fmlaResult = 1.2;
      mcell.setCellValue(fmlaResult);
      assertEquals(fmlaResult, mcell.getNumericCellValue());
    }
  }
Exemplo n.º 6
0
  /**
   * Returns a 2D double array representing the excel data.
   *
   * <p>In the case of an error, null is returned. In this case, call {@link #getErrMsg()} to see
   * the error message.
   *
   * @return the excel file data.
   */
  public List<Vector> getData() {
    if (sheet == null) {
      return null;
    }

    int size = sheet.getLastRowNum() + 1;
    List<List<Double>> cols = new ArrayList<>(numField);
    for (int i = 0; i < numField; i++) {
      cols.add(new ArrayList<Double>(size));
    }
    for (int i = 0; i < size; i++) {
      Row r = sheet.getRow(i);
      if (r == null) {
        msg = String.format("Error: cannot read row %d", i + 1);
        return null;
      }
      for (int j = 0; j < numField; j++) {
        Cell c = r.getCell(j);
        if (c == null
            || (c.getCellType() != Cell.CELL_TYPE_NUMERIC
                && c.getCellType() != Cell.CELL_TYPE_FORMULA)) {
          msg = String.format("Error: cannot read row %d cell %d", i, j);
          if (j == 0) {
            return parse(cols);
          }
          return null;
        }

        try {
          cols.get(j).add(c.getNumericCellValue());
        } catch (Exception ex) {
          msg =
              String.format(
                  "Error: cannot read row %d cell %d\nMessage: %s", i, j, ex.getMessage());
          return null;
        }
      }
    }
    return parse(cols);
  }
  public void testModifyArrayCells_setCellType() {
    Workbook workbook = _testDataProvider.createWorkbook();
    Sheet sheet = workbook.createSheet();

    // single-cell array formulas behave just like normal cells -
    // changing cell type removes the array formula and associated cached result
    CellRange<? extends Cell> srange =
        sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5"));
    Cell scell = srange.getTopLeftCell();
    assertEquals(Cell.CELL_TYPE_FORMULA, scell.getCellType());
    assertEquals(0.0, scell.getNumericCellValue());
    scell.setCellType(Cell.CELL_TYPE_STRING);
    assertEquals(Cell.CELL_TYPE_STRING, scell.getCellType());
    scell.setCellValue("string cell");
    assertEquals("string cell", scell.getStringCellValue());

    // once you create a multi-cell array formula, you cannot change the type of its cells
    CellRange<? extends Cell> mrange =
        sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3"));
    for (Cell mcell : mrange) {
      try {
        assertEquals(Cell.CELL_TYPE_FORMULA, mcell.getCellType());
        mcell.setCellType(Cell.CELL_TYPE_NUMERIC);
        fail("expected exception");
      } catch (IllegalStateException e) {
        CellReference ref = new CellReference(mcell);
        String msg =
            "Cell "
                + ref.formatAsString()
                + " is part of a multi-cell array formula. You cannot change part of an array.";
        assertEquals(msg, e.getMessage());
      }
      // a failed invocation of Cell.setCellType leaves the cell
      // in the state that it was in prior to the invocation
      assertEquals(Cell.CELL_TYPE_FORMULA, mcell.getCellType());
      assertTrue(mcell.isPartOfArrayFormulaGroup());
    }
  }
Exemplo n.º 8
0
 /**
  * 获得指定位置的值,返回object,可为数值,字符串,布尔类型,null类型
  *
  * @param column
  * @return
  */
 public Object getCellValueObject(int rowNum, int column) {
   // 定义返回的数组
   Object tempObject = null;
   row = sheet.getRow(rowNum);
   cell = row.getCell(column);
   // 判断值类型
   switch (cell.getCellType()) {
       // 字符串类型
     case Cell.CELL_TYPE_STRING:
       tempObject = cell.getRichStringCellValue().getString();
       // System.out.println(cell.getRichStringCellValue().getString());
       break;
       // 数值类型
     case Cell.CELL_TYPE_NUMERIC:
       if (DateUtil.isCellDateFormatted(cell)) {
         tempObject = cell.getDateCellValue();
         // System.out.println(cell.getDateCellValue());
       } else {
         tempObject = cell.getNumericCellValue();
         // System.out.println(cell.getNumericCellValue());
       }
       break;
       // 布尔类型
     case Cell.CELL_TYPE_BOOLEAN:
       tempObject = cell.getBooleanCellValue();
       // System.out.println(cell.getBooleanCellValue());
       break;
       // 数学公式类型
     case Cell.CELL_TYPE_FORMULA:
       tempObject = cell.getCellFormula();
       // System.out.println(cell.getCellFormula());
       break;
     default:
       System.out.println();
   }
   return tempObject;
 }
Exemplo n.º 9
0
  /**
   * Compute width of a single cell
   *
   * @param cell the cell whose width is to be calculated
   * @param defaultCharWidth the width of a single character
   * @param formatter formatter used to prepare the text to be measured
   * @param useMergedCells whether to use merged cells
   * @return the width in pixels
   */
  public static double getCellWidth(
      Cell cell, int defaultCharWidth, DataFormatter formatter, boolean useMergedCells) {

    Sheet sheet = cell.getSheet();
    Workbook wb = sheet.getWorkbook();
    Row row = cell.getRow();
    int column = cell.getColumnIndex();

    int colspan = 1;
    for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
      CellRangeAddress region = sheet.getMergedRegion(i);
      if (containsCell(region, row.getRowNum(), column)) {
        if (!useMergedCells) {
          // If we're not using merged cells, skip this one and move on to the next.
          return -1;
        }
        cell = row.getCell(region.getFirstColumn());
        colspan = 1 + region.getLastColumn() - region.getFirstColumn();
      }
    }

    CellStyle style = cell.getCellStyle();
    int cellType = cell.getCellType();

    // for formula cells we compute the cell width for the cached formula result
    if (cellType == Cell.CELL_TYPE_FORMULA) cellType = cell.getCachedFormulaResultType();

    Font font = wb.getFontAt(style.getFontIndex());

    AttributedString str;
    TextLayout layout;

    double width = -1;
    if (cellType == Cell.CELL_TYPE_STRING) {
      RichTextString rt = cell.getRichStringCellValue();
      String[] lines = rt.getString().split("\\n");
      for (int i = 0; i < lines.length; i++) {
        String txt = lines[i] + defaultChar;

        str = new AttributedString(txt);
        copyAttributes(font, str, 0, txt.length());

        if (rt.numFormattingRuns() > 0) {
          // TODO: support rich text fragments
        }

        layout = new TextLayout(str.getIterator(), fontRenderContext);
        if (style.getRotation() != 0) {
          /*
           * Transform the text using a scale so that it's height is increased by a multiple of the leading,
           * and then rotate the text before computing the bounds. The scale results in some whitespace around
           * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
           * is added by the standard Excel autosize.
           */
          AffineTransform trans = new AffineTransform();
          trans.concatenate(
              AffineTransform.getRotateInstance(style.getRotation() * 2.0 * Math.PI / 360.0));
          trans.concatenate(AffineTransform.getScaleInstance(1, fontHeightMultiple));
          width =
              Math.max(
                  width,
                  ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth)
                      + cell.getCellStyle().getIndention());
        } else {
          width =
              Math.max(
                  width,
                  ((layout.getBounds().getWidth() / colspan) / defaultCharWidth)
                      + cell.getCellStyle().getIndention());
        }
      }
    } else {
      String sval = null;
      if (cellType == Cell.CELL_TYPE_NUMERIC) {
        // Try to get it formatted to look the same as excel
        try {
          sval = formatter.formatCellValue(cell, dummyEvaluator);
        } catch (Exception e) {
          sval = String.valueOf(cell.getNumericCellValue());
        }
      } else if (cellType == Cell.CELL_TYPE_BOOLEAN) {
        sval = String.valueOf(cell.getBooleanCellValue()).toUpperCase();
      }
      if (sval != null) {
        String txt = sval + defaultChar;
        str = new AttributedString(txt);
        copyAttributes(font, str, 0, txt.length());

        layout = new TextLayout(str.getIterator(), fontRenderContext);
        if (style.getRotation() != 0) {
          /*
           * Transform the text using a scale so that it's height is increased by a multiple of the leading,
           * and then rotate the text before computing the bounds. The scale results in some whitespace around
           * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
           * is added by the standard Excel autosize.
           */
          AffineTransform trans = new AffineTransform();
          trans.concatenate(
              AffineTransform.getRotateInstance(style.getRotation() * 2.0 * Math.PI / 360.0));
          trans.concatenate(AffineTransform.getScaleInstance(1, fontHeightMultiple));
          width =
              Math.max(
                  width,
                  ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth)
                      + cell.getCellStyle().getIndention());
        } else {
          width =
              Math.max(
                  width,
                  ((layout.getBounds().getWidth() / colspan) / defaultCharWidth)
                      + cell.getCellStyle().getIndention());
        }
      }
    }
    return width;
  }
Exemplo n.º 10
0
  protected SCell importCell(Cell poiCell, int row, SSheet sheet) {

    SCell cell = sheet.getCell(row, poiCell.getColumnIndex());
    cell.setCellStyle(importCellStyle(poiCell.getCellStyle()));

    switch (poiCell.getCellType()) {
      case Cell.CELL_TYPE_NUMERIC:
        cell.setNumberValue(poiCell.getNumericCellValue());
        break;
      case Cell.CELL_TYPE_STRING:
        RichTextString poiRichTextString = poiCell.getRichStringCellValue();
        if (poiRichTextString != null && poiRichTextString.numFormattingRuns() > 0) {
          SRichText richText = cell.setupRichTextValue();
          importRichText(poiCell, poiRichTextString, richText);
        } else {
          cell.setStringValue(poiCell.getStringCellValue());
        }
        break;
      case Cell.CELL_TYPE_BOOLEAN:
        cell.setBooleanValue(poiCell.getBooleanCellValue());
        break;
      case Cell.CELL_TYPE_FORMULA:
        cell.setFormulaValue(poiCell.getCellFormula());
        // ZSS-873
        if (isImportCache() && !poiCell.isCalcOnLoad() && !mustCalc(cell)) {
          ValueEval val = null;
          switch (poiCell.getCachedFormulaResultType()) {
            case Cell.CELL_TYPE_NUMERIC:
              val = new NumberEval(poiCell.getNumericCellValue());
              break;
            case Cell.CELL_TYPE_STRING:
              RichTextString poiRichTextString0 = poiCell.getRichStringCellValue();
              if (poiRichTextString0 != null && poiRichTextString0.numFormattingRuns() > 0) {
                SRichText richText = new RichTextImpl();
                importRichText(poiCell, poiRichTextString0, richText);
                val = new StringEval(richText.getText());
              } else {
                val = new StringEval(poiCell.getStringCellValue());
              }
              break;
            case Cell.CELL_TYPE_BOOLEAN:
              val = BoolEval.valueOf(poiCell.getBooleanCellValue());
              break;
            case Cell.CELL_TYPE_ERROR:
              val = ErrorEval.valueOf(poiCell.getErrorCellValue());
              break;
            case Cell.CELL_TYPE_BLANK:
            default:
              // do nothing
          }
          if (val != null) {
            ((AbstractCellAdv) cell).setFormulaResultValue(val);
          }
        }
        break;
      case Cell.CELL_TYPE_ERROR:
        cell.setErrorValue(PoiEnumConversion.toErrorCode(poiCell.getErrorCellValue()));
        break;
      case Cell.CELL_TYPE_BLANK:
        // do nothing because spreadsheet model auto creates blank cells
      default:
        // TODO log: leave an unknown cell type as a blank cell.
        break;
    }

    Hyperlink poiHyperlink = poiCell.getHyperlink();
    if (poiHyperlink != null) {
      String addr = poiHyperlink.getAddress();
      String label = poiHyperlink.getLabel();
      SHyperlink hyperlink =
          cell.setupHyperlink(
              PoiEnumConversion.toHyperlinkType(poiHyperlink.getType()),
              addr == null ? "" : addr,
              label == null ? "" : label);
      cell.setHyperlink(hyperlink);
    }

    Comment poiComment = poiCell.getCellComment();
    if (poiComment != null) {
      SComment comment = cell.setupComment();
      comment.setAuthor(poiComment.getAuthor());
      comment.setVisible(poiComment.isVisible());
      RichTextString poiRichTextString = poiComment.getString();
      if (poiRichTextString != null && poiRichTextString.numFormattingRuns() > 0) {
        importRichText(poiCell, poiComment.getString(), comment.setupRichText());
      } else {
        comment.setText(poiComment.toString());
      }
    }

    return cell;
  }
Exemplo n.º 11
0
 private static void confirmCell(
     Sheet sheet, int rowIx, int colIx, double expectedValue, String expectedFormula) {
   Cell cell = sheet.getRow(rowIx).getCell(colIx);
   assertEquals(expectedValue, cell.getNumericCellValue(), 0.0);
   assertEquals(expectedFormula, cell.getCellFormula());
 }