org.apache.poi.ss.usermodel.Cell Java Examples

The following examples show how to use org.apache.poi.ss.usermodel.Cell. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PerFileSheetV1d1.java    From tools with Apache License 2.0 6 votes vote down vote up
public static void create(Workbook wb, String sheetName) {
	int sheetNum = wb.getSheetIndex(sheetName);
	if (sheetNum >= 0) {
		wb.removeSheetAt(sheetNum);
	}
	Sheet sheet = wb.createSheet(sheetName);
	CellStyle headerStyle = AbstractSheet.createHeaderStyle(wb);	
	CellStyle centerStyle = AbstractSheet.createCenterStyle(wb);
	CellStyle wrapStyle = AbstractSheet.createLeftWrapStyle(wb);
	Row row = sheet.createRow(0);
	for (int i = 0; i < HEADER_TITLES.length; i++) {
		sheet.setColumnWidth(i, COLUMN_WIDTHS[i]*256);
		if (LEFT_WRAP[i]) {
			sheet.setDefaultColumnStyle(i, wrapStyle);
		} else if (CENTER_NOWRAP[i]) {
			sheet.setDefaultColumnStyle(i, centerStyle);
		}
		Cell cell = row.createCell(i);
		cell.setCellStyle(headerStyle);
		cell.setCellValue(HEADER_TITLES[i]);
	}
}
 
Example #2
Source File: PerFileSheet.java    From tools with Apache License 2.0 6 votes vote down vote up
public static void create(Workbook wb, String sheetName) {
	int sheetNum = wb.getSheetIndex(sheetName);
	if (sheetNum >= 0) {
		wb.removeSheetAt(sheetNum);
	}
	Sheet sheet = wb.createSheet(sheetName);
	CellStyle headerStyle = AbstractSheet.createHeaderStyle(wb);
	CellStyle centerStyle = AbstractSheet.createCenterStyle(wb);
	CellStyle wrapStyle = AbstractSheet.createLeftWrapStyle(wb);
	Row row = sheet.createRow(0);
	for (int i = 0; i < HEADER_TITLES.length; i++) {
		sheet.setColumnWidth(i, COLUMN_WIDTHS[i]*256);
		if (LEFT_WRAP[i]) {
			sheet.setDefaultColumnStyle(i, wrapStyle);
		} else if (CENTER_NOWRAP[i]) {
			sheet.setDefaultColumnStyle(i, centerStyle);
		}
		Cell cell = row.createCell(i);
		cell.setCellStyle(headerStyle);
		cell.setCellValue(HEADER_TITLES[i]);
	}
}
 
Example #3
Source File: CellFinderTest.java    From xlsmapper with Apache License 2.0 6 votes vote down vote up
/**
 * セルが見つからない場合
 */
@Test
public void testFind_whenNotFoundException() {
    
    {
        Cell cell = CellFinder.query(sheet, "テスト", config).findWhenNotFoundException();
        
        assertThat(cell).isNotNull();
        assertThat(CellPosition.of(cell).toString()).isEqualTo("B4");
        assertThat(getCellContents(cell)).isEqualTo("テスト");
    }
    
    {
        // セルが見つからない場合
        assertThatThrownBy(() -> CellFinder.query(sheet, "あいう", config).findWhenNotFoundException())
            .isInstanceOf(CellNotFoundException.class);
    }
    
}
 
Example #4
Source File: ExcelExportUtil.java    From base with MIT License 6 votes vote down vote up
private static void createRow(Sheet sheet, Map<String, Object> rowData, List<String> mapping,
		List<CellStyle> styles, int startRowNum) {
	Row row = sheet.createRow(startRowNum);
	for (int i = 0; i < mapping.size(); i++) {
		String name = mapping.get(i);
		Object obj = rowData.get(name);
		Cell newCell = row.createCell(i);
		CellStyle style = styles.get(i);
		newCell.setCellStyle(style);
		if (obj != null) {
			if (obj instanceof Date) {
				newCell.setCellValue((Date) obj);
			} else if (obj instanceof BigDecimal) {
				double dd = ((BigDecimal) obj).doubleValue();
				newCell.setCellValue(dd);
			} else {
				newCell.setCellValue(obj.toString());
			}
		}
	}
}
 
Example #5
Source File: DateDataObjectFieldFlatFileLoader.java    From Open-Lowcode with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected boolean putContentInCell(E currentobject, Cell cell, String context) {
	DataObjectField<?, E> field = currentobject.payload.lookupSimpleFieldOnName(name);
	if (field == null)
		throw new RuntimeException("field " + name + " could not be looked-up on " + currentobject.getName());
	if (!(field instanceof DateDataObjectField))
		throw new RuntimeException("Expected field " + name
				+ " would be of type DateDataObjectField but in reality, it is " + field.getClass().toString());
	DateDataObjectField<E> datefield = (DateDataObjectField<E>) currentobject.payload.lookupSimpleFieldOnName(name);

	if (cellStyle == null)
		cellStyle = FlatFileExtractor.createDateStyle(cell.getSheet().getWorkbook(), this.formatasstring);

	cell.setCellValue((datefield.getValue()));
	cell.setCellStyle(cellStyle);
	return true;
}
 
Example #6
Source File: BaseCellConverter.java    From xlsmapper with Apache License 2.0 6 votes vote down vote up
@Override
public T toObject(final Cell cell) throws XlsMapperException {

    final ProcessCase processCase = ProcessCase.Load;
    final String formattedValue = Utils.trim(configuration.getCellFormatter().format(cell), trimmed);

    // デフォルト値の設定
    if(isEmptyCell(formattedValue, cell) && defaultValue.isPresent(processCase)) {
        return defaultValue.get(processCase);
    }

    // 数式のセルの場合、予め評価しておく
    final Cell evaluatedCell;
    if(cell.getCellTypeEnum().equals(CellType.FORMULA)) {
        final Workbook workbook = cell.getSheet().getWorkbook();
        final CreationHelper helper = workbook.getCreationHelper();
        final FormulaEvaluator evaluator = helper.createFormulaEvaluator();

        evaluatedCell = evaluator.evaluateInCell(cell);
    } else {
        evaluatedCell = cell;
    }

    return parseCell(evaluatedCell, formattedValue);
}
 
Example #7
Source File: BaseFormulaEvaluator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected static void setCellType(Cell cell, CellValue cv) {
    CellType cellType = cv.getCellTypeEnum();
    switch (cellType) {
        case BOOLEAN:
        case ERROR:
        case NUMERIC:
        case STRING:
            cell.setCellType(cellType);
            return;
        case BLANK:
            // never happens - blanks eventually get translated to zero
            throw new IllegalArgumentException("This should never happen. Blanks eventually get translated to zero.");
        case FORMULA:
            // this will never happen, we have already evaluated the formula
            throw new IllegalArgumentException("This should never happen. Formulas should have already been evaluated.");
        default:
            throw new IllegalStateException("Unexpected cell value type (" + cellType + ")");
    }
}
 
Example #8
Source File: Excel2007FileRecordReader.java    From components with Apache License 2.0 6 votes vote down vote up
private int getCellNumber(Row headerRow) {
  Map<Integer, Cell> cellMap = ((StreamingRow)headerRow).getCellMap();
  
  int max = 0;
  boolean emptyRow = true;
  for(Map.Entry<Integer, Cell> entry : cellMap.entrySet()) {
    Integer key = entry.getKey();
    if(key != null) {
      emptyRow = false;
      max = Math.max(max, key);
    }
  }
  
  if(emptyRow) {
    return 0;
  }
  
  return max + 1;
}
 
Example #9
Source File: PackageInfoSheetV2d1.java    From tools with Apache License 2.0 6 votes vote down vote up
public static void create(Workbook wb, String sheetName) {
	int sheetNum = wb.getSheetIndex(sheetName);
	if (sheetNum >= 0) {
		wb.removeSheetAt(sheetNum);
	}
	Sheet sheet = wb.createSheet(sheetName);
	CellStyle headerStyle = AbstractSheet.createHeaderStyle(wb);
	CellStyle defaultStyle = AbstractSheet.createLeftWrapStyle(wb);
	Row row = sheet.createRow(0);
	for (int i = 0; i < HEADER_TITLES.length; i++) {
		sheet.setColumnWidth(i, COLUMN_WIDTHS[i]*256);
		sheet.setDefaultColumnStyle(i, defaultStyle);
		Cell cell = row.createCell(i);
		cell.setCellStyle(headerStyle);
		cell.setCellValue(HEADER_TITLES[i]);
	}
}
 
Example #10
Source File: CellValueFormatter.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public String formatCellValue(Cell cell, FormulaEvaluator evaluator) {

    if (cell == null) {
        return "";
    }

    int cellType = cell.getCellType();
    if (cellType == Cell.CELL_TYPE_FORMULA) {
        if (evaluator == null) {
            return cell.getCellFormula();
        }
        cellType = evaluator.evaluateFormulaCell(cell);
    }
    switch (cellType) {
        case Cell.CELL_TYPE_NUMERIC :
            return getFormattedNumberString(cell);
        case Cell.CELL_TYPE_STRING :
            return cell.getRichStringCellValue().getString();
        case Cell.CELL_TYPE_BOOLEAN :
            return String.valueOf(cell.getBooleanCellValue());
        case Cell.CELL_TYPE_BLANK :
            return "";
    }
    throw new RuntimeException("Unexpected celltype (" + cellType + ")");
}
 
Example #11
Source File: CellValueServer.java    From autopoi with Apache License 2.0 6 votes vote down vote up
/**
 * 获取cell的值
 * 
 * @param object
 * @param excelParams
 * @param cell
 * @param titleString
 */
public Object getValue(IExcelDataHandler dataHanlder, Object object, Cell cell, Map<String, ExcelImportEntity> excelParams, String titleString) throws Exception {
	ExcelImportEntity entity = excelParams.get(titleString);
	String xclass = "class java.lang.Object";
	if (!(object instanceof Map)) {
		Method setMethod = entity.getMethods() != null && entity.getMethods().size() > 0 ? entity.getMethods().get(entity.getMethods().size() - 1) : entity.getMethod();
		Type[] ts = setMethod.getGenericParameterTypes();
		xclass = ts[0].toString();
	}
	Object result = getCellValue(xclass, cell, entity);
	if (entity != null) {
		result = hanlderSuffix(entity.getSuffix(), result);
		//update-begin-author:taoYan date:20180807 for:多值替换
		result = replaceValue(entity.getReplace(), result,entity.isMultiReplace());
		//update-end-author:taoYan date:20180807 for:多值替换
	}
	result = hanlderValue(dataHanlder, object, result, titleString);
	return getValueByType(xclass, result, entity);
}
 
Example #12
Source File: LongestMatchColumnWidthStyleStrategy.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
    if (isHead) {
        return cell.getStringCellValue().getBytes().length;
    }
    CellData cellData = cellDataList.get(0);
    CellDataTypeEnum type = cellData.getType();
    if (type == null) {
        return -1;
    }
    switch (type) {
        case STRING:
            return cellData.getStringValue().getBytes().length;
        case BOOLEAN:
            return cellData.getBooleanValue().toString().getBytes().length;
        case NUMBER:
            return cellData.getNumberValue().toString().getBytes().length;
        default:
            return -1;
    }
}
 
Example #13
Source File: PerformanceTest.java    From excel-streaming-reader with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
  for(int i = 0; i < 10; i++) {
    long start = System.currentTimeMillis();
    InputStream is = new FileInputStream(new File("/Users/thundermoose/Downloads/SampleXLSFile_6800kb.xlsx"));
    try(Workbook workbook = StreamingReader.builder()
        .rowCacheSize(100)    // number of rows to keep in memory (defaults to 10)
        .bufferSize(4096)     // buffer size to use when reading InputStream to file (defaults to 1024)
        .open(is)) {

      for(Row r : workbook.getSheet("test")) {
        for(Cell c : r) {
          //do nothing
        }
      }
    }

    long end = System.currentTimeMillis();
    System.out.println("Time: " + (end - start) + "ms");
  }
}
 
Example #14
Source File: Prd4434IT.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testExcelExport() throws Exception {
  final MasterReport report = DebugReportRunner.parseGoldenSampleReport( "Prd-3625.prpt" );

  final ByteArrayOutputStream bout = new ByteArrayOutputStream();
  ExcelReportUtil.createXLS( report, bout );

  final HSSFWorkbook wb = new HSSFWorkbook( new ByteArrayInputStream( bout.toByteArray() ) );
  final HSSFSheet sheetAt = wb.getSheetAt( 0 );
  final HSSFRow row = sheetAt.getRow( 0 );
  final HSSFCell cell0 = row.getCell( 0 );
  assertEquals( Cell.CELL_TYPE_NUMERIC, cell0.getCellType() );
  assertEquals( "yyyy-MM-dd", cell0.getCellStyle().getDataFormatString() );
  final HSSFCell cell1 = row.getCell( 1 );
  assertEquals( Cell.CELL_TYPE_NUMERIC, cell1.getCellType() );
  assertEquals( "#,###.00;(#,###.00)", cell1.getCellStyle().getDataFormatString() );
}
 
Example #15
Source File: ReviewersSheet.java    From tools with Apache License 2.0 6 votes vote down vote up
public static void create(Workbook wb, String sheetName) {
	int sheetNum = wb.getSheetIndex(sheetName);
	if (sheetNum >= 0) {
		wb.removeSheetAt(sheetNum);
	}
	Sheet sheet = wb.createSheet(sheetName);
	CellStyle headerStyle = AbstractSheet.createHeaderStyle(wb);
	CellStyle centerStyle = AbstractSheet.createCenterStyle(wb);
	CellStyle wrapStyle = AbstractSheet.createLeftWrapStyle(wb);
	Row row = sheet.createRow(0);
	for (int i = 0; i < HEADER_TITLES.length; i++) {
		sheet.setColumnWidth(i, COLUMN_WIDTHS[i]*256);
		if (LEFT_WRAP[i]) {
			sheet.setDefaultColumnStyle(i, wrapStyle);
		} else if (CENTER_NOWRAP[i]) {
			sheet.setDefaultColumnStyle(i, centerStyle);
		}
		Cell cell = row.createCell(i);
		cell.setCellStyle(headerStyle);
		cell.setCellValue(HEADER_TITLES[i]);
	}
}
 
Example #16
Source File: DocumentSheet.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * @param comparer
 * @throws SpdxCompareException 
 * @throws InvalidSPDXAnalysisException 
 */
private void importLicenseListVersions(SpdxComparer comparer) throws SpdxCompareException, InvalidSPDXAnalysisException {
	Cell cell = sheet.getRow(getFirstDataRow()).createCell(LICENSE_LIST_VERSION_COL);
	if (comparer.isLicenseListVersionEqual()) {
		setCellEqualValue(cell);
	} else {
		setCellDifferentValue(cell);
	}
	// data rows
	for (int i = 0; i < comparer.getNumSpdxDocs(); i++) {
		cell = sheet.getRow(getFirstDataRow()+i+1).createCell(LICENSE_LIST_VERSION_COL);
		if (comparer.getSpdxDoc(i).getCreationInfo().getLicenseListVersion() != null) {
			cell.setCellValue(comparer.getSpdxDoc(i).getCreationInfo().getLicenseListVersion());
		}
	}
}
 
Example #17
Source File: PropertyTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Applies the drawn borders to a Sheet. The borders that are applied are
 * the ones that have been drawn by the {@link #drawBorders} and
 * {@link #drawBorderColors} methods.
 *
 * @param sheet
 *            - {@link Sheet} on which to apply borders
 */
public void applyBorders(Sheet sheet) {
    Workbook wb = sheet.getWorkbook();
    for (Map.Entry<CellAddress, Map<String, Object>> entry : _propertyTemplate
            .entrySet()) {
        CellAddress cellAddress = entry.getKey();
        if (cellAddress.getRow() < wb.getSpreadsheetVersion().getMaxRows()
                && cellAddress.getColumn() < wb.getSpreadsheetVersion()
                        .getMaxColumns()) {
            Map<String, Object> properties = entry.getValue();
            Row row = CellUtil.getRow(cellAddress.getRow(), sheet);
            Cell cell = CellUtil.getCell(row, cellAddress.getColumn());
            CellUtil.setCellStyleProperties(cell, properties);
        }
    }
}
 
Example #18
Source File: ExcelExportOfTemplateUtil.java    From jeasypoi with Apache License 2.0 6 votes vote down vote up
private void setForEeachCellValue(boolean isCreate, Row row, int columnIndex, Object t, List<ExcelTemplateParams> columns, Map<String, Object> map) throws Exception {
	for (int i = 0, max = columnIndex + columns.size(); i < max; i++) {
		if (row.getCell(i) == null)
			row.createCell(i);
	}
	for (int i = 0, max = columns.size(); i < max; i++) {
		boolean isNumber = false;
		String tempStr = new String(columns.get(i).getName());
		if (isNumber(tempStr)) {
			isNumber = true;
			tempStr = tempStr.replace(NUMBER_SYMBOL, "");
		}
		map.put(teplateParams.getTempParams(), t);
		String val = eval(tempStr, map).toString();
		if (isNumber && StringUtils.isNotEmpty(val)) {
			row.getCell(i + columnIndex).setCellValue(Double.parseDouble(val));
			row.getCell(i + columnIndex).setCellType(Cell.CELL_TYPE_NUMERIC);
		} else {
			row.getCell(i + columnIndex).setCellValue(val);
		}
		row.getCell(i + columnIndex).setCellStyle(columns.get(i).getCellStyle());
		tempCreateCellSet.add(row.getRowNum() + "_" + (i + columnIndex));
	}

}
 
Example #19
Source File: DictionaryServiceImpl.java    From nimrod with MIT License 6 votes vote down vote up
private List<Map<Integer, Cell>> uploadAndReadExcel(MultipartFile multipartFile) throws IOException {
    List<Map<Integer, Cell>> list = new ArrayList<>();
    Workbook workbook = ExcelUtil.getWorkbook(Objects.requireNonNull(multipartFile.getOriginalFilename()), multipartFile.getInputStream());
    if (workbook != null) {
        Sheet sheet = workbook.getSheetAt(0);
        int rowIndex;
        for (rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
            Row row = sheet.getRow(rowIndex);
            int cellIndex;
            Map<Integer, Cell> map = new HashMap<>(1);
            for (cellIndex = 0; cellIndex < row.getLastCellNum(); cellIndex++) {
                map.put(cellIndex, row.getCell(cellIndex));
            }
            list.add(map);
        }
    }
    return list.isEmpty() ? null : list;
}
 
Example #20
Source File: ExcelCellFormatter.java    From tutorials with MIT License 5 votes vote down vote up
public String getCellStringValue(Cell cell) {
    DataFormatter formatter = new DataFormatter();
    return formatter.formatCellValue(cell);
}
 
Example #21
Source File: StreamingReaderTest.java    From excel-streaming-reader with Apache License 2.0 5 votes vote down vote up
@Test
public void testFormulaWithDifferentTypes() throws Exception {
  try(
    InputStream is = new FileInputStream(new File("src/test/resources/formula_test.xlsx"));
    Workbook wb = StreamingReader.builder().open(is)
  ) {
    Sheet sheet = wb.getSheetAt(0);
    Iterator<Row> rowIterator = sheet.rowIterator();

    Row next = rowIterator.next();
    Cell cell = next.getCell(0);

    assertThat(cell.getCellType(), is(CellType.STRING));

    next = rowIterator.next();
    cell = next.getCell(0);

    assertThat(cell.getCellType(), is(CellType.FORMULA));
    assertThat(cell.getCachedFormulaResultTypeEnum(), is(CellType.STRING));

    next = rowIterator.next();
    cell = next.getCell(0);

    assertThat(cell.getCellType(), is(CellType.FORMULA));
    assertThat(cell.getCachedFormulaResultTypeEnum(), is(CellType.BOOLEAN));

    next = rowIterator.next();
    cell = next.getCell(0);

    assertThat(cell.getCellType(), is(CellType.FORMULA));
    assertThat(cell.getCachedFormulaResultTypeEnum(), is(CellType.NUMERIC));
  }
}
 
Example #22
Source File: NonStandardLicensesSheetV1d1.java    From tools with Apache License 2.0 5 votes vote down vote up
@Override
public String getLicenseName(int rowNum) {
	Row row = sheet.getRow(rowNum);
	if (row == null) {
		return null;
	}
	Cell licenseNameCell = row.getCell(LICENSE_NAME_COL);
	if (licenseNameCell == null) {
		return null;
	}
	return licenseNameCell.getStringCellValue();
}
 
Example #23
Source File: ExcelTempletService.java    From jeecg with Apache License 2.0 5 votes vote down vote up
/**
  * 得到某个格子的值 已经对过时方法进行更新
  * 
  * @param cell
  *            格子对象
  * @return 格子的值
  */
public static String getCellValueString(Cell cell) {
  if (cell == null) {
   return null;
  }
  // 时间对象 特殊处理
  int dataFormat = cell.getCellStyle().getDataFormat();
  
  if (dataFormat == 14 || dataFormat == 178 || dataFormat == 180 || dataFormat == 181
    || dataFormat == 182) {
	  	return getDateValue(cell);
  } 
  String value = null;
  switch (cell.getCellType()) {
	   case Cell.CELL_TYPE_NUMERIC :
	    value = new DecimalFormat("0.##########").format(cell.getNumericCellValue());
	    break;
	   case Cell.CELL_TYPE_STRING :
	    // value = cell.getStringCellValue();
	    value = cell.getRichStringCellValue().toString();
	    break;
	   case Cell.CELL_TYPE_FORMULA :
	    value = String.valueOf(cell.getCellFormula());
	    break;
	   case Cell.CELL_TYPE_BLANK :
	    // value = String.valueOf(cell.getStringCellValue());
	    value = String.valueOf(cell.getRichStringCellValue().toString());
	    break;
	   case Cell.CELL_TYPE_BOOLEAN :
	    value = String.valueOf(cell.getBooleanCellValue());
	    break;
	   case Cell.CELL_TYPE_ERROR :
	    value = String.valueOf(cell.getErrorCellValue());
	    break;
  }
  return value;
 }
 
Example #24
Source File: ExcelLogWriter.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
public void writeBody(Map<String, Map<String, List<Integer>>> dataMap) {
  CellStyle cellStyle = this.setStyle();

  for (Entry<String, Map<String, List<Integer>>> keyEntry : dataMap.entrySet()) {
    Row titleRow = sheet.createRow(sheet.getLastRowNum() + 1);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellStyle(cellStyle);
    titleCell.setCellValue(keyEntry.getKey());

    for (Entry<String, List<Integer>> dataEntry : keyEntry.getValue().entrySet()) {
      sheet.autoSizeColumn(0);
      sheet.autoSizeColumn(1);
      Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
      Cell dataCell1 = dataRow.createCell(0);
      dataCell1.setCellValue(dataEntry.getKey());
      Cell dataCell2 = dataRow.createCell(1);
      if (!CollectionUtils.isEmpty(dataEntry.getValue())) {
        dataCell2.setCellValue(
            dataEntry
                .getValue()
                .stream()
                .map(num -> String.valueOf(num))
                .collect(Collectors.joining(",")));
      }
    }
  }
}
 
Example #25
Source File: SessionSequenceFlatFileLoader.java    From Open-Lowcode with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected boolean putContentInCell(E currentobject, Cell cell, String context) {
	DataObjectProperty<E> property = propertyextractor.extract(currentobject);
	if (property == null)
		throw new RuntimeException("Technical error in inserting start date: property not found");
	if (!(property instanceof Session))
		throw new RuntimeException("Technical error in inserting start date: property not of correct class: "
				+ property.getClass().getName());
	@SuppressWarnings("unchecked")
	Session<E, F> session = (Session<E, F>) property;
	Integer sequence = session.getSequence();
	if (sequence != null)
		cell.setCellValue(session.getSequence().doubleValue());
	return false;
}
 
Example #26
Source File: ExcelUtil.java    From phone with Apache License 2.0 5 votes vote down vote up
/**
    * 记录每一列对应的column
    * @param sheet
    * @param columnJson
    * @param rowNumber
    * @return
    */
private static Map<Integer, String> readSheetHead(HSSFSheet sheet, JSONObject columnJson, int rowNumber) {
	if (logger.isDebugEnabled()) {
		logger.debug("readSheetHead(HSSFSheet, JSONObject, int) - start"); //$NON-NLS-1$
	}

	Map<Integer, String> map = new Hashtable<Integer, String>();
	if(sheet!=null){
		HSSFRow row = sheet.getRow(rowNumber++);
		if (row!=null) {
			Iterator<Cell> iterator = row.cellIterator();
			while (iterator.hasNext()) {
				Cell cell = iterator.next();
				if (cell!=null) {
					String cellValue = cell.getStringCellValue();
					if (StringUtils.isNotBlank(cellValue) && columnJson.containsKey(cellValue)) {
						map.put(cell.getColumnIndex(), columnJson.getString(cellValue));// 记录cell每一列对应的columnName
					}
				}
			}
		}
	}

	if (logger.isDebugEnabled()) {
		logger.debug("readSheetHead(HSSFSheet, JSONObject, int) - end"); //$NON-NLS-1$
	}
	return map;
}
 
Example #27
Source File: MultipleChoiceDataObjectFieldFlatFileLoaderColumn.java    From Open-Lowcode with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected boolean putContentInCell(E currentobject, Cell cell, String context) {
	@SuppressWarnings("unchecked")
	DataObjectField<?, E> field = currentobject.payload.lookupSimpleFieldOnName(name);
	if (field == null)
		throw new RuntimeException("field " + name + " could not be looked-up on " + currentobject.getName());
	if (!(field instanceof MultipleChoiceDataObjectField))
		throw new RuntimeException("Expected field " + name
				+ " would be of type ChoiceDataObjectField but in reality, it is " + field.getClass().toString());
	@SuppressWarnings("unchecked")
	MultipleChoiceDataObjectField<?, E> choicefield = (MultipleChoiceDataObjectField<?, E>) field;
	cell.setCellValue(choicefield.getStorageString());
	return false;
}
 
Example #28
Source File: SpreadsheetReader.java    From taro with MIT License 5 votes vote down vote up
/**
 * Returns the trimmed content of the cell as a String, or an empty String
 * if the cell doesn't exist or is empty.
 */
public String getStringValue(Cell cell) {
    if (cell == null) {
        return "";
    } else {
        String value = cell.getStringCellValue();
        if (value != null) {
            value = value.trim();
        }
        return value;
    }
}
 
Example #29
Source File: CrosstabXLSExporter.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
protected int buildDataMatrix(Sheet sheet, CrossTab cs, int rowOffset, int columnOffset, CreationHelper createHelper, MeasureFormatter measureFormatter)
		throws JSONException {

	CellStyle cellStyleForNA = buildNACellStyle(sheet);

	Map<Integer, CellStyle> decimalFormats = new HashMap<Integer, CellStyle>();
	int endRowNum = 0;
	for (int i = 0; i < cs.getDataMatrix().length; i++) {
		for (int j = 0; j < cs.getDataMatrix()[0].length; j++) {
			String text = cs.getDataMatrix()[i][j];
			int rowNum = rowOffset + i;
			int columnNum = columnOffset + j;
			Row row = sheet.getRow(rowNum);
			if (row == null) {
				row = sheet.createRow(rowNum);
			}
			endRowNum = rowNum;
			Cell cell = row.createCell(columnNum);
			try {
				double value = Double.parseDouble(text);
				int decimals = measureFormatter.getFormatXLS(i, j);
				Double valueFormatted = measureFormatter.applyScaleFactor(value, i, j);
				cell.setCellValue(valueFormatted);
				cell.setCellType(this.getCellTypeNumeric());
				cell.setCellStyle(getNumberFormat(decimals, decimalFormats, sheet, createHelper, cs.getCellType(i, j)));
			} catch (NumberFormatException e) {
				logger.debug("Text " + text + " is not recognized as a number");
				cell.setCellValue(createHelper.createRichTextString(text));
				cell.setCellType(this.getCellTypeString());
				cell.setCellStyle(cellStyleForNA);
			}

		}
	}
	return endRowNum;
}
 
Example #30
Source File: ReviewersSheet.java    From tools with Apache License 2.0 5 votes vote down vote up
public String getReviewer(int rowNum) {
	Row row = sheet.getRow(rowNum);
	if (row == null) {
		return null;
	}
	Cell reviewer = row.getCell(REVIEWER_COL);
	if (reviewer == null) {
		return null;
	}
	return reviewer.getStringCellValue();
}