public static void insertDedicatedStyleCell(XSSFRow row,int col,XSSFCellStyle style,String value){ String message="XSSFRow or XSSFCellStyle must not be null!"; Objects.requireNonNull(row, () -> message); Objects.requireNonNull(style, () -> message); XSSFCell cell=createCellIfNotPresent(row,col); setCellProperties(createCellIfNotPresent(row, col), value, style); }
public static void writeXLSXFile() throws IOException { // @SuppressWarnings("resource") XSSFWorkbook wbObj = new XSSFWorkbook(); XSSFSheet sheet = wbObj.createSheet(sheetName); for (int row = 0; row < tableData.size(); row++) { XSSFRow rowObj = sheet.createRow(row); rowData = tableData.get(row); for (int col = 0; col < rowData.size(); col++) { XSSFCell cell = rowObj.createCell(col); cell.setCellValue(rowData.get(col)); logger.info("Writing " + row + " " + col + " " + rowData.get(col)); } } FileOutputStream fileOut = new FileOutputStream(excelFileName); wbObj.write(fileOut); wbObj.close(); fileOut.flush(); fileOut.close(); }
public Object get(XSSFCell cell) { if (cell != null) { int cellType = cell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_NUMERIC: return cell.getNumericCellValue(); case Cell.CELL_TYPE_BOOLEAN: return cell.getBooleanCellValue(); default: try { return cell.getStringCellValue(); } catch (IllegalStateException mismatch) { return null; } } } else { return null; } }
private static String microsoftExcelDocumentToString(InputStream inputStream) throws IOException, OpenXML4JException, XmlException { StringBuilder sb = new StringBuilder(); try (InputStream excelStream = new BufferedInputStream(inputStream)) { if (POIFSFileSystem.hasPOIFSHeader(excelStream)) { // Before 2007 format files POIFSFileSystem excelFS = new POIFSFileSystem(excelStream); ExcelExtractor excelExtractor = new ExcelExtractor(excelFS); sb.append(excelExtractor.getText()); excelExtractor.close(); } else { // New format XSSFWorkbook workBook = new XSSFWorkbook(excelStream); int numberOfSheets = workBook.getNumberOfSheets(); for (int i = 0; i < numberOfSheets; i++) { XSSFSheet sheet = workBook.getSheetAt(0); Iterator<Row> rowIterator = sheet.rowIterator(); while (rowIterator.hasNext()) { XSSFRow row = (XSSFRow) rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { XSSFCell cell = (XSSFCell) cellIterator.next(); sb.append(cell.toString()); sb.append(" "); } sb.append("\n"); } sb.append("\n"); } } } return sb.toString(); }
/** * Gets the cell value. * * @param cell the cell * @return the cell value */ private String getCellValue( XSSFCell cell ) { if (cell != null) { switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_BLANK: return null; case XSSFCell.CELL_TYPE_BOOLEAN: return String.valueOf( cell.getBooleanCellValue() ); case XSSFCell.CELL_TYPE_NUMERIC: return String.valueOf( ( int ) cell.getNumericCellValue() ); case XSSFCell.CELL_TYPE_STRING: return cell.getRichStringCellValue().toString(); } } return null; }
/** * Gets the cell value. * * @param cell the cell * @return the cell value */ private String getCellValue( XSSFCell cell ) { if (cell != null) { switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_BLANK: return null; case XSSFCell.CELL_TYPE_BOOLEAN: return String.valueOf( cell.getBooleanCellValue() ); case XSSFCell.CELL_TYPE_NUMERIC: return String.valueOf( cell.getNumericCellValue() ); case XSSFCell.CELL_TYPE_STRING: return cell.getRichStringCellValue().toString(); } } return null; }
/** * Gets the cell value. * * @param cell the cell * @return the cell value */ private String getCellValue( XSSFCell cell ) { if (cell != null) { switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_BLANK: return null; case XSSFCell.CELL_TYPE_BOOLEAN: return String.valueOf( cell.getBooleanCellValue() ); case XSSFCell.CELL_TYPE_NUMERIC: { String useValue = String.valueOf( cell.getNumericCellValue() ); if ( useValue.endsWith( ".0" ) ) return useValue.split( "\\." )[0]; else return useValue; } case XSSFCell.CELL_TYPE_STRING: return cell.getRichStringCellValue().toString(); } } return null; }
private String getCellValue( XSSFCell cell ) { if (cell != null ) { switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_BLANK: return null; case XSSFCell.CELL_TYPE_BOOLEAN: return String.valueOf( cell.getBooleanCellValue() ); case XSSFCell.CELL_TYPE_NUMERIC: return String.valueOf( cell.getNumericCellValue() ); case XSSFCell.CELL_TYPE_STRING: return cell.getRichStringCellValue().toString(); } } return null; }
public void updateCellValue(String cellPosition, String value) throws Exception { String sheetNumTxt = cellPosition.indexOf("[")>-1 ? cellPosition.substring(cellPosition.indexOf("[")) : null; if(sheetNumTxt != null) { this.sheetNum = new Integer(sheetNumTxt.substring(0,sheetNumTxt.length()-1)); cellPosition = cellPosition.substring(cellPosition.indexOf("[")); } else { this.sheetNum = 0; } worksheet = workbook.getSheetAt(this.sheetNum); CellReference c = new CellReference(cellPosition); XSSFCell cell = worksheet.getRow(c.getRow()).getCell(c.getCol()); if(cell == null) throw new Exception("Invalid cell reference:" + cellPosition); if(value == null) { cell.setCellType(XSSFCell.CELL_TYPE_BLANK); } else if(cell.getCellType()==XSSFCell.CELL_TYPE_FORMULA) { this.setCellFormula(cell, value); } else { cell.setCellValue(value); } }
public void updateCellValue(String xslSourcePath, String xslDestPath, int sheetNum, String cellPosition, String value) throws Exception { // load Excel file, this.loadExcel(xslSourcePath, sheetNum); CellReference c = new CellReference(cellPosition); XSSFCell cell = worksheet.getRow(c.getRow()).getCell(c.getCol()); if(cell == null) throw new Exception("Invalid cell reference:" + cellPosition); if(value == null) { cell.setCellType(XSSFCell.CELL_TYPE_BLANK); } else if(cell.getCellType()==XSSFCell.CELL_TYPE_FORMULA) { this.setCellFormula(cell, value); } else { cell.setCellValue(value); } // close source and save destination this.saveExcel(xslDestPath); }
/** * Read the Excel 2010 * * @param path * the path of the excel file * @return * @throws IOException */ public static String readXlsx(String path) throws IOException { InputStream is = new FileInputStream(path); XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is); StringBuffer sb = new StringBuffer(""); // Read the Sheet for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) { XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet); if (xssfSheet == null) { continue; } // Read the Row for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) { XSSFRow xssfRow = xssfSheet.getRow(rowNum); if (xssfRow != null) { XSSFCell no = xssfRow.getCell(0); XSSFCell name = xssfRow.getCell(1); sb.append(no + ":" + name); sb.append(";"); } } } return sb.toString().substring(0, sb.toString().length() - 1); }
@Override public ValidationResult validate(XSSFCell cell) { if (cell.getCellType() == Cell.CELL_TYPE_STRING) { String stringCellValue = cell.getStringCellValue(); int length; if (stringCellValue == null) { length = 0; } else { length = stringCellValue.length(); } if (!operator.check((double) length)) { return new ValidationResultImpl(cell.getSheet().getSheetName(), cell.getReference(), false, "Error!"); } } else { // TODO how to handle this situation } return null; }
protected String stringValueOf(CellValue value) { switch (value.getCellType()) { case XSSFCell.CELL_TYPE_STRING: return value.getStringValue(); case XSSFCell.CELL_TYPE_NUMERIC: return String.valueOf(value.getNumberValue()); case XSSFCell.CELL_TYPE_BLANK: return ""; case XSSFCell.CELL_TYPE_BOOLEAN: return String.valueOf(value.getBooleanValue()); case XSSFCell.CELL_TYPE_ERROR: return "error"; default: return "unknown"; } }
/** * 获取单元格字符串值 * * @param cell * @return * */ public static String getStrCellVal(XSSFCell cell) { if (cell == null) { // 如果参数对象为空, // 则直接退出! return null; } switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_STRING: return cell.getStringCellValue(); case XSSFCell.CELL_TYPE_BOOLEAN: return cell.getBooleanCellValue() ? "true" : "false"; default: // 抛出异常 throw new XlsxTmplError(MessageFormat.format( ERR_CELL_TYPE, getSheetIndex(cell) + 1, getSheetName(cell), String.valueOf(cell.getRowIndex() + 1), getColName(cell.getColumnIndex()), String.class.getName(), getCellTypeName(cell) )); } }
/** * 获取单元格类型名称 * * @param cell * @return * */ public static String getCellTypeName(XSSFCell cell) { if (cell == null) { return "null"; } switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_BLANK: return "CELL_TYPE_BLANK"; case XSSFCell.CELL_TYPE_BOOLEAN: return "CELL_TYPE_BOOLEAN"; case XSSFCell.CELL_TYPE_ERROR: return "CELL_TYPE_ERROR"; case XSSFCell.CELL_TYPE_FORMULA: return "CELL_TYPE_FORMULA"; case XSSFCell.CELL_TYPE_NUMERIC: return "CELL_TYPE_NUMERIC"; case XSSFCell.CELL_TYPE_STRING: return "CELL_TYPE_STRING"; default: return "unknown"; } }
public static Object getValue(XSSFSheet sheet, int row, int col) { try { XSSFRow xrow = sheet.getRow(row); XSSFCell cell = xrow.getCell(col); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: return cell.getNumericCellValue(); case Cell.CELL_TYPE_STRING: return (new DateComponentFormatter( ComponentManager.getInstance().getComponentFormatDefaults().getSelectedDateFormat())) .stringToValue(cell.getStringCellValue()); } } catch (ParseException e) { e.printStackTrace(); } return null; }
private String fromXSSFRowtoCSV(XSSFRow row){ StringBuffer csvRow = new StringBuffer(); int l = row.getLastCellNum(); for (int i=0;i<l;i++){ XSSFCell cell = row.getCell((short)i); String cellValue = ""; if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) { cellValue = ""; } else if (cell.getCellType()== HSSFCell.CELL_TYPE_STRING){ cellValue = "\"" + cell.getStringCellValue() + "\""; } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){ double value = cell.getNumericCellValue(); cellValue = getNumberFormat().format(value); cellValue = "\"" + cellValue + "\""; } csvRow.append(cellValue); if (i<l){ csvRow.append(getCsvDelimiter().toCharArray()[0]); } } return csvRow.toString(); }
@Test public void createXLSXModifyProtected() throws IOException { System.out.println("createXLSXModifyProtected"); //creates sheet XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet(); XSSFRow row = sheet.createRow(0); XSSFCell cell = row.createCell(0); cell.setCellValue("Gravado"); sheet.protectSheet("54321"); //saves sheet new File("target/.output-file/xlsx").mkdirs(); workbook.write(new FileOutputStream("target/.output-file/xlsx/ModifyProtected.xlsx")); //read again and check XSSFWorkbook workbook2 = new XSSFWorkbook(new FileInputStream("target/.output-file/xlsx/ModifyProtected.xlsx")); Assert.assertEquals("Gravado", workbook2.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); }
public static boolean compareTwoRows(XSSFRow row1, XSSFRow row2) { if ((row1 == null) && (row2 == null)) { return true; } else if ((row1 == null) || (row2 == null)) { return false; } int firstCell1 = row1.getFirstCellNum(); int lastCell1 = row1.getLastCellNum(); boolean equalRows = true; // Compare all cells in a row for (int i = firstCell1; i <= lastCell1; i++) { XSSFCell cell1 = row1.getCell(i); XSSFCell cell2 = row2.getCell(i); if (!compareTwoCells(cell1, cell2)) { equalRows = false; break; } } return equalRows; }
private void fillExtraFields(String tablename, Object id, XSSFRow row, LinkedHashSet<String> de, int startCol) throws SQLException { // ExtraFields if (id != null && de != null) { String sql = "Select * from " + MyDBI.delimitL("ExtraFields") + " WHERE " + MyDBI.delimitL("tablename") + "='" + tablename + "' AND " + MyDBI.delimitL("id") + "=" + id; ResultSet rs2 = DBKernel.getResultSet(sql, false); if (rs2 != null && rs2.first()) { do { String s = rs2.getString("attribute"); int j=0; for (String e : de) { if (s.equalsIgnoreCase(e)) { XSSFCell cell = row.getCell(startCol+j); if (cell == null) cell = row.createCell(startCol+j); cell.setCellValue(rs2.getString("value")); break; } j++; } } while (rs2.next()); } } }
/** * Get the value of the excel-cell as String. * * @param workbook * workbook (excel) for evaluating cell formulas * @param cell * cell (excel) * * @return the value of the excel-cell as String */ static String cellValues2String(XSSFWorkbook workbook, XSSFCell cell) { if (cell == null) { return null; } switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { return new SimpleDateFormat(JExUnitConfig.getStringProperty(JExUnitConfig.ConfigKey.DATE_PATTERN)) .format(cell.getDateCellValue()); } else { return String.valueOf(cell.getNumericCellValue()); } case XSSFCell.CELL_TYPE_STRING: return cell.getStringCellValue(); case XSSFCell.CELL_TYPE_FORMULA: return evaluateCellFormula(workbook, cell); case XSSFCell.CELL_TYPE_BLANK: return cell.getStringCellValue(); case XSSFCell.CELL_TYPE_BOOLEAN: return String.valueOf(cell.getBooleanCellValue()); case XSSFCell.CELL_TYPE_ERROR: return String.valueOf(cell.getErrorCellValue()); } return null; }
/** * Evaluate the formula of the given cell. * * @param workbook * workbook (excel) for evaluating the cell formula * @param cell * cell (excel) * * @return the value of the excel-call as string (the formula will be executed) */ static String evaluateCellFormula(XSSFWorkbook workbook, XSSFCell cell) { FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); CellValue cellValue = evaluator.evaluate(cell); switch (cellValue.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: return String.valueOf(cellValue.getBooleanValue()); case Cell.CELL_TYPE_NUMERIC: return String.valueOf(cellValue.getNumberValue()); case Cell.CELL_TYPE_STRING: return cellValue.getStringValue(); default: return null; } }
public void writeSheet(String key, Vector<String[]> sheetVector, XSSFWorkbook workbook){ XSSFSheet worksheet = workbook.createSheet(key); int count=0;//keeps track of rows; one below the row int because of header row final Pattern NUMERIC = Pattern.compile("^\\d+.?\\d*$"); //for each row, create the row in excel for (int row=0; row<sheetVector.size();row++){ XSSFRow row1 = worksheet.createRow( count); count++; //for each col, write it to that row. for (int col=0; col<sheetVector.get(0).length;col++){ XSSFCell cell = row1.createCell(col); String val = sheetVector.get(row)[col]; if(val != null && !val.isEmpty() && NUMERIC.matcher(val).find()) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(Double.parseDouble(val)); continue; } cell.setCellValue(sheetVector.get(row)[col]); } } }
public void writeSheet(String key, Vector<String[]> sheetVector, XSSFWorkbook workbook) { XSSFSheet worksheet = workbook.createSheet(key); int count=0;//keeps track of rows; one below the row int because of header row final Pattern NUMERIC = Pattern.compile("^\\d+.?\\d*$"); //for each row, create the row in excel for (int row=0; row<sheetVector.size();row++){ XSSFRow row1 = worksheet.createRow( count); count++; //for each col, write it to that row.7 for (int col=0; col<sheetVector.get(row).length;col++) { XSSFCell cell = row1.createCell(col); if(sheetVector.get(row)[col] != null) { String val = sheetVector.get(row)[col]; //Check if entire value is numeric - if so, set cell type and parseDouble, else write normally if(val != null && !val.isEmpty() && NUMERIC.matcher(val).find()) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(Double.parseDouble(val)); } else { cell.setCellValue(sheetVector.get(row)[col].replace("\"", "")); } } } } }
public void writeSheet(String key, Vector<String[]> sheetVector, XSSFWorkbook workbook) { XSSFSheet worksheet = workbook.createSheet(key); int count=0;//keeps track of rows; one below the row int because of header row final Pattern NUMERIC = Pattern.compile("^\\d+.?\\d*$"); //for each row, create the row in excel for (int row=0; row<sheetVector.size();row++){ XSSFRow row1 = worksheet.createRow( count); count++; //for each col, write it to that row.7 for (int col=0; col<sheetVector.get(row).length;col++){ XSSFCell cell = row1.createCell(col); if(sheetVector.get(row)[col] != null) { String val = sheetVector.get(row)[col]; //Check if entire value is numeric - if so, set cell type and parseDouble, else write normally if(val != null && !val.isEmpty() && NUMERIC.matcher(val).find()) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(Double.parseDouble(val)); } else { cell.setCellValue(sheetVector.get(row)[col].replace("\"", "")); } } } } }
@Override protected void printHeader(List<String> header, ByteArrayOutputStream out) { wb = new XSSFWorkbook(); sheet = wb.createSheet("NextReports"); XSSFRow headerRow = sheet.createRow(0); int col = 0; if (header != null) { for (String s : header) { XSSFCell cell = headerRow.createCell(col); cell.setCellType(XSSFCell.CELL_TYPE_STRING); if (s == null) { s = ""; } cell.setCellValue(wb.getCreationHelper().createRichTextString(s)); col++; } } }
@Override public EmpVO mappingColumn(XSSFRow row) { XSSFCell cell0 = row.getCell(0); XSSFCell cell1 = row.getCell(1); XSSFCell cell2 = row.getCell(2); EmpVO vo = new EmpVO(); vo.setEmpNo(new BigDecimal(cell0.getNumericCellValue())); vo.setEmpName(EgovExcelUtil.getValue(cell1)); vo.setJob(EgovExcelUtil.getValue(cell2)); log.debug("########### vo is " + vo.getEmpNo()); log.debug("########### vo is " + vo.getEmpName()); log.debug("########### vo is " + vo.getJob()); return vo; }
@Override public ZipVO mappingColumn(XSSFRow row) { XSSFCell cell0 = row.getCell(0); XSSFCell cell1 = row.getCell(1); XSSFCell cell2 = row.getCell(2); XSSFCell cell3 = row.getCell(3); XSSFCell cell4 = row.getCell(4); XSSFCell cell5 = row.getCell(5); XSSFCell cell6 = row.getCell(6); XSSFCell cell7 = row.getCell(7); ZipVO vo = new ZipVO(); vo.setZipNo(new BigDecimal(cell0.getNumericCellValue())); vo.setSerNo(new BigDecimal(cell1.getNumericCellValue())); vo.setSidoNm(EgovExcelUtil.getValue(cell2)); vo.setCggNm(EgovExcelUtil.getValue(cell3)); vo.setUmdNm(EgovExcelUtil.getValue(cell4)); vo.setBdNm(EgovExcelUtil.getValue(cell5)); vo.setJibun(EgovExcelUtil.getValue(cell6)); vo.setRegId(EgovExcelUtil.getValue(cell7)); return vo; }
/** * 셀 Data type 테스트 * 셀의 값이 Null 인경우 오류발생 */ @Test public void testCellDataFormat() throws Exception { StringBuffer sb = new StringBuffer(); sb.append(fileLocation).append("/").append("testDataFormat.xlsx"); XSSFWorkbook wb = excelService.loadXSSFWorkbook(sb.toString()); XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row = sheet.getRow(7); XSSFCell cell = row.getCell(0); assertEquals("2009/04/01", EgovExcelUtil.getValue(cell)); row = sheet.getRow(8); cell = row.getCell(0); assertEquals("2009/04/02", EgovExcelUtil.getValue(cell)); }
public static XSSFWorkbook convertToXSSFWorkbook(String html) { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("Sheet1"); Document doc = Jsoup.parse(html); for (Element table : doc.select("table")) { int rownum = 0; for (Element row : table.select("tr")) { XSSFRow exlrow = sheet.createRow(rownum++); int cellnum = 0; for (Element tds : row.select("td")) { StringUtils.isNumeric(""); XSSFCell cell = exlrow.createCell(cellnum++); cell.setCellValue(tds.text()); } } } return workbook; }
public static XSSFCell createCellIfNotPresent(XSSFRow row, int colIndex) { String message = "XSSFRow must not be null!"; Objects.requireNonNull(row, () -> message); XSSFCell cell = row.getCell(colIndex); if (Objects.isNull(cell)) { cell = row.createCell(colIndex); } return cell; }
/** * @param cell * @param value * @param style */ public static void setCellProperties(XSSFCell cell, String value, XSSFCellStyle style) { Assert.notNull(cell, "cell must not be null!"); // fill year cell.setCellValue(value); cell.setCellStyle(style); }
/** * @param sheet * @param pos 位置【row,col】 * @param style * @param v */ public static void setCell(final XSSFWorkbook wb,final XSSFSheet sheet,int[] pos,CellStyle style,FontStyle font,String v){ XSSFRow row = sheet.getRow(pos[0]); XSSFCell cell = CellValueUtil.createCellIfNotPresent(row, pos[1]); XSSFCellStyle _style = Objects .requireNonNull(new XSSFCellStyleLib(wb).get(style), "specified style not defined!"); XSSFFont _font = Objects .requireNonNull(new XSSFFontStyleLib(wb).get(font), "specified font not defined!"); _style.setFont(_font); setCellProperties(cell, v, _style); }
public static XSSFCell createCellIfNotPresent(XSSFRow row,int colIndex){ String message="XSSFRow must not be null!"; Objects.requireNonNull(row, () -> message); XSSFCell cell=row.getCell(colIndex); if(Objects.isNull(cell)){ cell=row.createCell(colIndex); } return cell; }
/** * @param cell * @param value * @param style */ public static void setCellProperties(XSSFCell cell,String value,XSSFCellStyle style){ Assert.notNull(cell, "cell must not be null!"); //fill year cell.setCellValue(value); cell.setCellStyle(style); }