/** * 获取excel列表头 * * @param titleRow excel行 * @param clz 类型 * @return ExcelHeader集合 * @throws InstantiationException 异常 * @throws IllegalAccessException 异常 */ public static Map<Integer, ExcelHeader> getHeaderMap(Row titleRow, Class<?> clz) throws InstantiationException, IllegalAccessException { List<ExcelHeader> headers = getHeaderList(clz); Map<Integer, ExcelHeader> maps = new HashMap<>(); for (Cell c : titleRow) { String title = c.getStringCellValue(); for (ExcelHeader eh : headers) { if (eh.getTitle().equals(title.trim())) { maps.put(c.getColumnIndex(), eh); break; } } } return maps; }
public Object getCellValue(Cell cell){ Object value = null; DecimalFormat df = new DecimalFormat("0"); //格式化number String字符 DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字 switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: value = cell.getRichStringCellValue().getString(); break; case Cell.CELL_TYPE_NUMERIC: if("General".equals(cell.getCellStyle().getDataFormatString())) { value = df.format(cell.getNumericCellValue()); } else { value = df2.format(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BOOLEAN: value = cell.getBooleanCellValue(); break; case Cell.CELL_TYPE_BLANK: value = ""; break; default: break; } return value; }
@Override public IRow readRow() { SheetData vData = getLocalData(); int vRowIndex = vData.getCurrentIndex(); if (vRowIndex < vData.getRowCount()) { Row vRow = vData.getSheet().getRow(vRowIndex); String[] vTitles = vData.getTitles(); Cell[] vValues = new Cell[vTitles.length]; for (int i = 0; i < vTitles.length; ++i) { Cell vCell = vRow.getCell(i, MissingCellPolicy.CREATE_NULL_AS_BLANK); vValues[i] = vCell; } vData.setCurrentIndex(vRowIndex + 1); return new RowExcelImpl(vRowIndex, vTitles, vValues); } // read over, remove the local data removeLocalData(); return null; }
public void set(int sheetIndex, int x_index, int y_index, String value) { try { if (wb == null) throw new Exception("未打开文件"); Sheet sheet = wb.getSheetAt(sheetIndex); Row row = null; Cell cell = null; row = sheet.getRow(x_index); if (row == null) { row = sheet.createRow(x_index); } cell = row.getCell(y_index); if (cell == null) { cell = row.createCell(y_index); } cell.setCellValue(value); save(); } catch (Exception e) { logger.error(e.getMessage()); } }
/** * Método que se encarga de leer el libro de excel * cuya ruta recibimos en el constructor y devuelve una lista * de ciudadanos * @return lista de Usuarios de la base de datos */ public List<CitizenDB> readExcelFile(){ List<CitizenDB> citizens = new ArrayList<CitizenDB>(); // para cada una de las hojas presentes en el documento de excel for(int i=0;i < workbook.getNumberOfSheets();i++){ XSSFSheet sheet = this.workbook.getSheetAt(i); Iterator<Row> rowIterator = sheet.iterator(); Row row; int counter = 0; //para cada fila de la hoja while(rowIterator.hasNext()){ row = rowIterator.next(); if (counter > 0) { //omitimos la cabecera (hay que mirar si hay un metodo de la API) Iterator<Cell> cellIterator = row.cellIterator(); int j = 0; CitizenDB user = new CitizenDB(); while (cellIterator.hasNext()) this.insertCitizenField(user, j++, cellIterator.next()); user.setPassword(new GenerationPassword().passwordGenerator()); citizens.add(user); } counter++; } } return citizens; }
private String getInsertStatementForCell(String userId, Cell cell) { String answer = null; switch (cell.getColumnIndex()) { case 1: answer = getInsertStatement(userId, 2237); break; case 2: answer = getInsertStatement(userId, 4352); break; case 3: answer = getInsertStatement(userId, 3657); break; case 4: answer = getInsertStatement(userId, 5565); break; } return answer; }
private void setSheetData(SheetData data, String group) { data.setCurrentGroup(group); // start from 1 data.setCurrentIndex(1); // get sheet Sheet vSheet = getWorkBook().getSheet(group); Assert.notNull(vSheet, "Can't get sheet with name: " + group); data.setSheet(vSheet); // get row number int vRowCount = vSheet.getLastRowNum() + 1; data.setRowCount(vRowCount); // get first row Row vRow = vSheet.getRow(0); Assert.notNull(vRow, "Invalid format: first row must be title"); // get column number int vColumnCount = vRow.getLastCellNum(); String[] vTitles = new String[vColumnCount]; // read titles for (int i = 0; i < vColumnCount; ++i) { Cell vCell = vRow.getCell(i); vTitles[i] = vCell.getStringCellValue(); } data.setTitles(vTitles); }
@Override public void next(ProgressListener listener) { currentRow++; while (currentRow < totalNumberOfRows + rowOffset && emptyRows[currentRow - rowOffset]) { currentRow++; } if (currentRow >= totalNumberOfRows + rowOffset) { throw new NoSuchElementException("No further row in excel sheet."); } currentRowCells = new Cell[attributeNames.length]; int columnCounter = 0; for (int c = 0; c < totalNumberOfColumns; c++) { if (!emptyColumns[c]) { currentRowCells[columnCounter] = sheet.getRow(currentRow).getCell(c + columnOffset); columnCounter++; } } // notifying progress listener if (listener != null) { listener.setCompleted(currentRow); } }
public void feedDetailsSheet(Sheet sheet, boolean exportAsTemplate, List<XLTestStep> xLTestSteps) { int index = 0; for (XLTestStep xLTestStep : xLTestSteps) { index++; Row row = sheet.createRow(index); Cell cell = row.createCell(STEPNAME_INDEX); cell.setCellValue(xLTestStep.getName()); cell = row.createCell(EXPECTED_OR_ACTION_INDEX); cell.setCellValue(xLTestStep.getExpected()); cell = row.createCell(RESULT_INDEX); if (exportAsTemplate) cell.setCellValue(""); else cell.setCellValue(xLTestStep.getActual()); cell = row.createCell(STATUS_INDEX); formatCellStatus(sheet, cell); if (exportAsTemplate) cell.setCellValue(""); else cell.setCellValue(Integer.parseInt(xLTestStep.getStatus())); } this.autoSize(sheet, new int[] { 0, 1, 2, 3 }); }
public void print () { Sheet sheet = getOrCreateSummary(); Iterator<Row> rows = sheet.rowIterator(); int index=0; while (rows.hasNext()) { Row row = (Row) rows.next(); System.out.println("Row ---> " + index); Spliterator<Cell> cells = row.spliterator(); cells.forEachRemaining(new Consumer<Cell> () { @Override public void accept(Cell cell) { System.out.print(cell.toString()); System.out.print(";"); } }); System.out.println(); index++; } }
/** * {@inheritDoc} */ @Override public String[] readLine(int line, boolean readResult) throws TechnicalException { final Sheet sheet = workbook.getSheetAt(0); final Row row = sheet.getRow(line); if (row == null || "".equals(readCell(row.getCell(0)))) { return null; } else { final String[] ret = readResult ? new String[columns.size()] : new String[columns.size() - 1]; Cell cell; for (int i = 0; i < ret.length; i++) { if ((cell = row.getCell(i)) == null) { ret[i] = ""; } else { ret[i] = readCell(cell); } } return ret; } }
protected void setCellValue(Cell sheetCell, Object value, Class<?> valueType, Object propId) { if (null != value) { if (!isNumeric(valueType)) { if (java.util.Date.class.isAssignableFrom(valueType)) { sheetCell.setCellValue((Date) value); } else { sheetCell.setCellValue(createHelper.createRichTextString(value.toString())); } } else { try { // parse all numbers as double, the format will determine how they appear final Double d = Double.parseDouble(value.toString()); sheetCell.setCellValue(d); } catch (final NumberFormatException nfe) { LOGGER.warning("NumberFormatException parsing a numeric value: " + nfe); sheetCell.setCellValue(createHelper.createRichTextString(value.toString())); } } } }
protected void formatCellStatus(Sheet sheet, Cell cell) { cell.setCellStyle(styles.get("status")); SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); ConditionalFormattingRule ruleGreen = sheetCF.createConditionalFormattingRule(ComparisonOperator.EQUAL, "1"); PatternFormatting fill1 = ruleGreen.createPatternFormatting(); fill1.setFillBackgroundColor(IndexedColors.GREEN.index); fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); // ConditionalFormattingRule ruleRed = sheetCF.createConditionalFormattingRule(ComparisonOperator.EQUAL, "0"); PatternFormatting fill2 = ruleRed.createPatternFormatting(); fill2.setFillBackgroundColor(IndexedColors.RED.index); fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND); // ConditionalFormattingRule ruleOrange = sheetCF.createConditionalFormattingRule(ComparisonOperator.EQUAL, "2"); PatternFormatting fill3 = ruleOrange.createPatternFormatting(); fill3.setFillBackgroundColor(IndexedColors.ORANGE.index); fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND); // String name = CellReference.convertNumToColString(cell.getColumnIndex()); String location = "$" + name + "$" + cell.getRowIndex() + ":$" + name + "$" + (cell.getRowIndex() + 1); CellRangeAddress[] regions = { CellRangeAddress.valueOf(location) }; ConditionalFormattingRule[] cfRules = new ConditionalFormattingRule[] { ruleGreen, ruleRed, ruleOrange }; sheetCF.addConditionalFormatting(regions, cfRules); }
/** * 向当前Sheet第一行(1-based)写入标题,若用户没有开启写入标题总开关(即{@link #isWriteTitle}为false), * 或者{@link #titles}为空则不会做任何操作 */ private void writeTitle() { if (!this.isWriteTitle || this.titles == null || this.titles.isEmpty()) { return; } this.currentRowInSheet++; Row row = this.currentSheetPO.createRow(this.currentRowInSheet); row.setHeight(this.rowHeight < 0 ? -1 : this.rowHeight); for (int i = 0; i < this.titles.size(); i++) { Cell cell = row.createCell(i); cell.setCellStyle(this.defaultTitleCellStyle); cell.setCellValue(this.titles.get(i)); } this.realRowInSheet++; this.realRowInExcel++; }
public static void main(String[] args) throws Throwable { SXSSFWorkbook wb = new SXSSFWorkbook(100); // keep 100 rows in memory, exceeding rows will be flushed to disk Sheet sh = wb.createSheet(); for (int rownum = 0; rownum < 1000; rownum++) { Row row = sh.createRow(rownum); Row row1 = sh.createRow(rownum); for (int cellnum = 0; cellnum < 10; cellnum++) { Cell cell = row.createCell(cellnum); String address = new CellReference(cell).formatAsString(); cell.setCellValue(address); } } // Rows with rownum < 900 are flushed and not accessible // for (int rownum = 0; rownum < 103857; rownum++) { // Assert.assertNull(sh.getRow(rownum)); // } // // // ther last 100 rows are still in memory // for (int rownum = 103857; rownum < 104857; rownum++) { // Assert.assertNotNull(sh.getRow(rownum)); // } File file = new File("C:\\Users\\FlyingHe\\Desktop", "datas.xlsx"); FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); // dispose of temporary files backing this workbook on disk wb.dispose(); }
private boolean getBooleanValue(Cell cell) { switch (getCellType(cell)) { case Cell.CELL_TYPE_BOOLEAN: return cell.getBooleanCellValue(); case Cell.CELL_TYPE_NUMERIC: return Double.compare(cell.getNumericCellValue(), 0) != 0; case Cell.CELL_TYPE_STRING: return Boolean.valueOf(cell.getStringCellValue()); default: return false; } }
/** * @param row 0-based index * @param column 0-based index */ public static void writeCell(Sheet sheet, int row, int column, String value) { Row r = sheet.getRow(row); if (r == null) { r = sheet.createRow(row); } Cell cell = r.getCell(column); if (cell == null) { cell = r.createCell(column, Cell.CELL_TYPE_STRING); } cell.setCellValue(value); }
public static void appendItemCn(BufferedWriter out, Cell cell1, Cell cell2) throws IOException { if (cell1 == null || cell2 == null) { return; } String name = cell2.getStringCellValue().replaceAll("( )+", "_").toLowerCase(); String value = cell1.getStringCellValue(); if(StringUtils.isEmpty(name) && StringUtils.isEmpty(value)){ return; } out.append(String.format("<string name=\"%s\">%s</string>", name, value)); out.newLine(); }
public static Short getShort(Cell cell) { if (isNullCell(cell)) { return null; } if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { return (short) cell.getNumericCellValue(); } if (Cell.CELL_TYPE_STRING == cell.getCellType()) { return Short.parseShort(cell.getStringCellValue()); } throw new RuntimeException("can not convertWithConstructor cell value to Short!"); }
public static Integer getInteger(Cell cell) { if (isNullCell(cell)) { return null; } if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { return (int) cell.getNumericCellValue(); } if (Cell.CELL_TYPE_STRING == cell.getCellType()) { return Integer.parseInt(cell.getStringCellValue()); } throw new RuntimeException("can not convertWithConstructor cell value to Integer!"); }
private Collection loadFromSpreadsheet(final InputStream excelFile)throws IOException { HSSFWorkbook workbook = new HSSFWorkbook(excelFile); data = new ArrayList(); Sheet sheet = workbook.getSheetAt(0); int numberOfColumns = countNonEmptyColumns(sheet); List rows = new ArrayList(); List rowData = new ArrayList(); for (Row row : sheet) { if (isEmpty(row)) { break; } else if(row.getRowNum() == 0 ) { //do nothing }else { rowData.clear(); for (int column = 0; column < numberOfColumns; column++) { Cell cell = row.getCell(column); rowData.add(objectFrom(workbook, cell)); } rows.add(rowData.toArray()); } } return rows; }
public List<List<String>> getData(int sheetNumber) { List<List<String>> data = new ArrayList<>(); XSSFSheet sheet = book.getSheetAt(sheetNumber); for (Row row : sheet) { List<String> rowData = new ArrayList<>(); for (Cell cell : row) { rowData.add(getAsString(cell)); } data.add(rowData); } return data; }
private String getAsString(Cell cell) { switch (cell.getCellTypeEnum()) { case NUMERIC: return String.valueOf(cell.getNumericCellValue()); case BOOLEAN: return String.valueOf(cell.getBooleanCellValue()); case STRING: return cell.getStringCellValue(); default: return ""; } }
/** * Adds the totals row to the report. Override this method to make any * changes. Alternately, the totals Row Object is accessible via * getTotalsRow() after report creation. To change the CellStyle used for * the totals row, use setFormulaStyle. For different totals cells to have * different CellStyles, override getTotalsStyle(). * * @param currentRow the current row * @param startRow the start row */ protected void addTotalsRow(final int currentRow, final int startRow) { totalsRow = sheet.createRow(currentRow); totalsRow.setHeightInPoints(30); Cell cell; int col = 0; for (final String propId : getPropIds()) { cell = totalsRow.createCell(col); setupTotalCell(cell, propId, currentRow, startRow, col); col++; } }
private int createHeader(Sheet sheet, int rowNum, String[] titles) { Row headerRow = sheet.createRow(rowNum); headerRow.setHeightInPoints(40); Cell headerCell; int[] cols = new int[titles.length]; for (int i = 0; i < titles.length; i++) { cols[i] = i; headerCell = headerRow.createCell(i); headerCell.setCellValue(titles[i]); headerCell.setCellStyle(styles.get("header")); } autoSize(sheet, cols); return rowNum; }
private int getCellType(Cell cell) { int vType = cell.getCellType(); if (vType == Cell.CELL_TYPE_FORMULA) { // 获取公式类型 vType = cell.getCachedFormulaResultType(); } return vType; }
public static String getString(Cell cell) { if (isNullCell(cell)) { return null; } if (Cell.CELL_TYPE_STRING == cell.getCellType()) { return cell.getStringCellValue(); } if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { return NumberUtil.numberStr(cell.getNumericCellValue()); } throw new RuntimeException("can not convertWithConstructor cell value to String!"); }
private static String getCellString(Cell cell) { if (cell.getCellTypeEnum() == CellType.FORMULA) { try { return String.valueOf(cell.getNumericCellValue()); } catch (Exception e) { return cell.getRichStringCellValue().toString(); } } else { return cell.toString(); } }
private List<String> getInsertStatementsForRow(Row row) { List<String> lines = new ArrayList<>(); Cell firstCell = row.getCell(0); if (firstCell != null) { String userId = firstCell.getStringCellValue(); if (isValidUserId(userId)) { lines.addAll(getInsertStatementsForRow(row, userId)); } } return lines; }
private Stream<String> getInsertStatementsForRow(Row row) { Cell firstCell = row.getCell(0); if (firstCell != null) { String userId = firstCell.getStringCellValue(); if (isValidUserId(userId)) { return getInsertStatementsForRow(row, userId); } } return Stream.empty(); }
/** * En función de la columna del excel leída, insertaremos un valor u otro * en el cliente * @param citizen * @param col columna en la que se encuentra la celda a tratar * @param cell La celda a tratar en cada momento */ private void insertCitizenField(CitizenDB citizen, int col,Cell cell) { switch(col){ case 0: citizen.setName(cell.getStringCellValue()); return; case 1: citizen.setSurname(cell.getStringCellValue()); return; case 2: citizen.setMail(cell.getStringCellValue()); return; case 3: citizen.setBirthday(cell.getDateCellValue()); return; case 4: citizen.setAddress(cell.getStringCellValue()); return; case 5: citizen.setNationality(cell.getStringCellValue()); return; case 6: citizen.setDNI(cell.getStringCellValue()); return; default: return; } }
/** * This method is ultimately used by either addDataRows() or * addHierarchicalDataRows() to actually add the data to the Sheet. * * @param sheetToAddTo the sheet to add to * @param rootItemId the root item id * @param row the row */ protected void addDataRow(final Sheet sheetToAddTo, final T rootItemId, final int row) { final Row sheetRow = sheetToAddTo.createRow(row); Object value; Class<?> valueType; Cell sheetCell; int col = 0; for (final String propId : getPropIds()) { value = getGridHolder().getPropertyValue(rootItemId, propId); valueType = getGridHolder().getPropertyType(propId); sheetCell = sheetRow.createCell(col); setupCell(sheetCell, value, valueType, propId, rootItemId, row, col); col++; } }
@Override public List<String> generate(Sheet sheet) { List<String> lines = new ArrayList<>(); for (Row row : sheet) { Cell firstCell = row.getCell(0); if (firstCell != null) { String userId = firstCell.getStringCellValue(); if (".".equals(userId.substring(1, 2))) { for (Cell cell : row) { if (cell.getColumnIndex() == 0) { continue; } if ("X".equals(cell.getStringCellValue())) { switch (cell.getColumnIndex()) { case 1: lines.add(getInsertStatement(userId, 2237)); break; case 2: lines.add(getInsertStatement(userId, 4352)); break; case 3: lines.add(getInsertStatement(userId, 3657)); break; case 4: lines.add(getInsertStatement(userId, 5565)); break; } } } } } } return lines; }
private void addInsertStatementsForRow(List<String> lines, Row row) { Cell firstCell = row.getCell(0); if (firstCell != null) { String userId = firstCell.getStringCellValue(); if (isValidUserId(userId)) { addInsertStatementsForRow(lines, row, userId); } } }
public static Boolean getBoolean(Cell cell) { if (isNullCell(cell)) { return null; } if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) { return cell.getBooleanCellValue(); } if (Cell.CELL_TYPE_STRING == cell.getCellType()) { String value = cell.getStringCellValue(); return "1".equals(value) || "是".equals(value); } throw new RuntimeException("can not convertWithConstructor cell value to Boolean!"); }
public static void CreateCell(Cell c, Row r, Sheet s, CellStyle cs, int colinaI, int colinaF, Object valorS, int linhaI, int linhaF) { c = r.createCell(linhaI); c.setCellStyle(cs); if(valorS instanceof Integer) c.setCellValue((Integer)valorS); else c.setCellValue((String)valorS); s.setColumnWidth(linhaI, linhaF*500); }
public static XSSFCell asNumber(XSSFRow row, int columnIndex, Number value) { XSSFCell cell = row.createCell(columnIndex, Cell.CELL_TYPE_NUMERIC); if (value != null) { cell.setCellValue(value.doubleValue()); } return cell; }
/** * Method parses a row of the body content and puts the related entry into the result list (entries). * If the row is invalid in any kind, no modification happens. If any of the parameters provided is null or invalid, * no modification happens. * * @param entries the list of entries, where the result of the row should be put in * @param langKeys the language information to parse the row correctly * @param row the row to be processed. */ private void parseContentBodyRow( List<MessageResourceEntry> entries, Map<Integer, Locale> langKeys, Row row, String type) { if (entries == null || row == null || langKeys == null || langKeys.isEmpty()) { return; } MessageResourceEntry entry = new MessageResourceEntry(); String code = getCellStringValue(row.getCell(this.keyColumn)); if (!StringUtils.isBlank(code)) { entry.setCodeId(StringUtils.trim(code)); for (int nameIndex = this.firstLanguageColumn; nameIndex <= langKeys.size(); nameIndex++) { Cell cell = row.getCell(nameIndex); String name = getCellStringValue(cell); if (!StringUtils.isBlank(name)) { Locale lang = langKeys.get(nameIndex); entry.addLang(lang, name); } } if (entry.size() > 0) { entry.setType(type); entries.add(entry); } } if (LOG.isDebugEnabled()) { LOG.debug(ToStringBuilder.reflectionToString(entry, ToStringStyle.SHORT_PREFIX_STYLE)); } }
public String get(int sheetIndex, int x_index, int y_index) { String str = ""; try { if (wb == null) throw new Exception("未打开文件"); HSSFCell cell = wb.getSheetAt(sheetIndex).getRow(x_index).getCell(y_index); cell.setCellType(Cell.CELL_TYPE_STRING);//处理读取xls时 单元格使用各类函数的数据读取问题 str = cell.getStringCellValue(); } catch (Exception e) { logger.error(e.getMessage()); } return str; }