List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook close
@Override public void close() throws IOException
From source file:ch.bfh.lca._15h.library.export.ExportToExcel.java
/*** * Prototype function. Not yet functional. * Allow to generate an age pyramid graphic in Excel by using an existing Excel Template. * @param language Language of the label in the Excel file * @param rows Arrays of rows to include in the listing * @param excelFilePath Path of the outputed file * @throws FileNotFoundException/*from ww w. ja v a 2 s . co m*/ * @throws IOException * @throws InvalidFormatException */ public static void exportToAgePyramid(Translation.TRANSLATION_LANGUAGE language, GenericResultRow[] rows, String excelFilePath) throws FileNotFoundException, IOException, InvalidFormatException { //open template URL url = Translation.class.getClassLoader() .getResource("ch/bfh/lca/_15h/library/export/template/alter-pyramide-v2.xlsx"); //Workbook wb = WorkbookFactory.create(new File(url.getPath())); XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(new File(url.getPath()))); Sheet sheet = wb.getSheetAt(0); //http://www.programming-free.com/2012/12/create-charts-in-excel-using-java.html //https://poi.apache.org/spreadsheet/quick-guide.html#NewWorkbook Row row; Cell cell; for (int i = 0; i < 20; i++) { row = sheet.getRow(i + 1); if (row == null) { row = sheet.createRow(i + 1); } for (int j = 0; j < 3; j++) { cell = row.getCell(j); if (cell == null) { cell = row.createCell(j); } switch (j) { case 0: cell.setCellValue(i); break; case 1: cell.setCellValue(i * j * -1); break; case 2: cell.setCellValue(i * j); break; } } } //redefine data range //http://thinktibits.blogspot.ch/2014/09/Excel-Insert-Format-Table-Apache-POI-Example.html XSSFSheet sheet1 = wb.getSheetAt(0); XSSFTable table = sheet1.getTables().get(0); CTTable cttable = table.getCTTable(); AreaReference my_data_range = new AreaReference(new CellReference(0, 0), new CellReference(20, 2)); /* Set Range to the Table */ cttable.setRef(my_data_range.formatAsString()); // cttable.setDisplayName("DATEN"); /* this is the display name of the table */ //cttable.setName("test"); /* This maps to "displayName" attribute in <table>, OOXML */ //cttable.setId(1L); //id attribute against table as long value /* //redefine data range Name rangeCell = wb.getName("DATEN"); //Set new range for named range //String reference = sheetName + "!$C$" + (deface + 1) + ":$C$" + (rowNum + deface); String reference = sheet.getSheetName() + "!$A$2:$C$20"; //Assigns range value to named range rangeCell.setRefersToFormula(reference); */ //write to the file FileOutputStream fileOut = new FileOutputStream(excelFilePath); wb.write(fileOut); fileOut.close(); wb.close(); }
From source file:com.celtris.exparse.parser.ExcelReader.java
License:Apache License
public List<SheetData<T>> readExcel(String absolutePath, Class<T> excelModelClass, boolean headerExtraction) throws IOException, InstantiationException, IllegalAccessException { FileInputStream file = new FileInputStream(new File(absolutePath)); // Create Workbook instance holding reference to .xlsx file XSSFWorkbook workbook = new XSSFWorkbook(file); DataFormatter objDefaultFormat = new DataFormatter(); FormulaEvaluator objFormulaEvaluator = new XSSFFormulaEvaluator(workbook); Iterator<Sheet> sheetIterator = workbook.iterator(); List<SheetData<T>> sheetDataList = new ArrayList<SheetData<T>>(workbook.getNumberOfSheets()); int sheetCount = 0; while (sheetIterator.hasNext()) { sheetCount++;//ww w .ja va2s.co m ExcelParser<T> excelParser = new ExcelParser<T>(headerExtraction, excelModelClass); Sheet sheet = sheetIterator.next(); Iterator<Row> rowIterator = sheet.iterator(); int rowCount = 0; // Evaluating header if (headerExtraction) { if (rowIterator.hasNext()) { rowCount++; Field[] fields = excelModelClass.getFields(); List<String> heaaderStr = new ArrayList<String>(fields.length); Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); String cellStrValue = cell.getStringCellValue(); heaaderStr.add(cellStrValue); } excelParser.processFieldAccordingToHeader(heaaderStr, sheet.getSheetName()); } } while (rowIterator.hasNext()) { rowCount++; Row row = rowIterator.next(); // For each row, iterate through all the columns Iterator<Cell> cellIterator = row.cellIterator(); List<String> rowStr = new ArrayList<String>(excelParser.parameterCount()); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); String cellStrValue = ""; switch (cell.getCellTypeEnum()) { case STRING: cellStrValue = cell.getStringCellValue(); break; case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { objFormulaEvaluator.evaluate(cell); cellStrValue = objDefaultFormat.formatCellValue(cell, objFormulaEvaluator); } else { cellStrValue = Double.toString(cell.getNumericCellValue()); } break; case BOOLEAN: cellStrValue = Boolean.toString(cell.getBooleanCellValue()); break; case FORMULA: cellStrValue = cell.getStringCellValue(); break; case BLANK: default: break; } rowStr.add(cellStrValue); } excelParser.processRow(rowStr, rowCount, sheet.getSheetName()); } SheetData<T> sheetData = new SheetData<T>(excelParser.getParsedObject(), sheet.getSheetName(), sheetCount); sheetDataList.add(sheetData); } file.close(); workbook.close(); return sheetDataList; }
From source file:com.hack23.cia.service.external.vdem.impl.VdemServiceImpl.java
License:Apache License
@Override public List<Question> getQuestions() { final List<Question> list = new ArrayList<>(); try {/*from w w w . j ava 2 s. c om*/ final XSSFWorkbook myWorkBook = new XSSFWorkbook( VdemServiceImpl.class.getResourceAsStream("/V-DemQuestionIDsv5(2016).xlsx")); final XSSFSheet mySheet = myWorkBook.getSheetAt(0); final Iterator<Row> rowIterator = mySheet.iterator(); rowIterator.next(); while (rowIterator.hasNext()) { final Row row = rowIterator.next(); final Question question = new Question(); if (row.getCell(0) == null) { question.setTag(row.getCell(1).toString()); question.setName(row.getCell(2).toString()); } else { question.setQuestionId(row.getCell(0).toString()); question.setTag(row.getCell(1).toString()); question.setName(row.getCell(2).toString()); } list.add(question); } myWorkBook.close(); } catch (final IOException e) { LOGGER.warn("Problem loading", e); } return list; }
From source file:com.infovity.iep.loader.util.SupplierLoaderUtil.java
public static ArrayList<String[]> getDataFromFile(File inputFile, String sheetName) { ArrayList<String[]> data = new ArrayList<String[]>(); File selectedFile = null;//from ww w. j a va 2s . c o m FileInputStream fis = null; ; XSSFWorkbook workbook = null; //inputFile = new File("C:\\Users\\INFOVITY-USER-029\\Desktop\\DataLoader\\Consolidated Supplier Data Capture Template v4.0.xlsx"); boolean sheetFound = false; XSSFSheet sheet = null; try { int sheetIndex = -1; fis = new FileInputStream(inputFile); workbook = new XSSFWorkbook(fis); int noOfSheets = workbook.getNumberOfSheets(); for (int i = 0; i < noOfSheets; i++) { sheet = workbook.getSheetAt(i); if (sheet.getSheetName().equals(sheetName)) { sheetFound = true; sheetIndex = i; selectedFile = inputFile; break; } } XSSFWorkbook myWorkBook; try { myWorkBook = new XSSFWorkbook(selectedFile); // Return first sheet from the XLSX workbook // XSSFSheet mySheet = myWorkBook.getSheetAt(0); // Get iterator to all the rows in current sheet Iterator<Row> rowIterator = sheet.iterator(); String query; String[] values = null; // Traversing over each row of XLSX file while (rowIterator.hasNext()) { Row row = rowIterator.next(); if (rowHasData(row) && (row.getRowNum() >= 9)) { int endColumn = row.getLastCellNum(); int startColumn = row.getFirstCellNum(); // For each row, iterate through each columns values = new String[endColumn + 2]; for (int i = startColumn; i < endColumn; i++) { String cellValue; Cell cell = row.getCell(i); values[0] = Integer.toString(row.getRowNum() + 1); if (cell != null) { if (cell.getCellType() == cell.CELL_TYPE_NUMERIC && DateUtil.isCellDateFormatted(cell)) { DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); Date cellDateValue = cell.getDateCellValue(); cellValue = df.format(cellDateValue); } else { cell.setCellType(cell.CELL_TYPE_STRING); cellValue = cell.getStringCellValue().replaceAll("'", ""); } if (!"".equals(cellValue) && cellValue != null) { values[i + 1] = cellValue; } else if (cellValue.isEmpty() || "".equals(cellValue)) { values[i + 1] = ""; } } else { values[i + 1] = ""; } } data.add(values); } } } catch (InvalidFormatException ex) { Logger.getLogger(SupplierLoaderUtil.class.getName()).log(Level.ERROR, null, ex); } } catch (IOException ex) { Logger.getLogger(SupplierLoaderUtil.class.getName()).log(Level.ERROR, null, ex); } finally { try { fis.close(); workbook.close(); } catch (IOException ex) { Logger.getLogger(SupplierLoaderUtil.class.getName()).log(Level.ERROR, null, ex); } } return data; }
From source file:com.khartec.waltz.web.endpoints.extracts.BaseDataExtractor.java
License:Open Source License
private byte[] convertExcelToByteArray(XSSFWorkbook workbook) throws IOException { ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); workbook.write(outByteStream);// w ww . j ava2 s. c om workbook.close(); return outByteStream.toByteArray(); }
From source file:com.metasoft.claim.service.impl.claim.ClaimImportServiceImpl.java
@Override @Transactional//w w w . j av a 2 s . co m public List<ImportError> saveFromFile(UploadedFile uploadedFile, SecUser user) throws Exception { List<ImportError> errorClaimNumbers = new ArrayList<ImportError>(); XSSFWorkbook workbook = null; try { InputStream input = new ByteArrayInputStream(uploadedFile.bytes); Date today = new Date(); // Using XSSF for xlsx format, for xls use HSSF workbook = new XSSFWorkbook(input); Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); Row row = rowIterator.next(); // iterating over each row int i = 1; int rowAt = 1; while (rowIterator.hasNext()) { i = 1; TblClaimRecovery claim = new TblClaimRecovery(); row = rowIterator.next(); try { // ? ? ? ? ? claim.setClaimNumber(StringUtils.trimToNull(row.getCell(i++).getStringCellValue())); claim.setPolicyNo(StringUtils.trimToNull(row.getCell(i++).getStringCellValue())); claim.setLicenseNumber(StringUtils.trimToNull(row.getCell(i++).getStringCellValue())); claim.setPartyLicenseNumber(StringUtils.trimToNull(row.getCell(i++).getStringCellValue())); claim.setAccidentDate(row.getCell(i++).getDateCellValue()); claim.setMaturityDate(row.getCell(i++).getDateCellValue()); } catch (Exception e) { ImportError importError = new ImportError(); importError.setReason("? " + rowAt + " " + i + " ?"); importError.setClaimNumber(StringUtils.isEmpty(claim.getClaimNumber()) ? "" : claim.getClaimNumber()); errorClaimNumbers.add(importError); continue; } String partyInsuranceName = StringUtils.trimToNull(row.getCell(i++).getStringCellValue()); if (partyInsuranceName != null) { claim.setPartyInsurance(insuranceDao.findByName(partyInsuranceName)); } claim.setClaimInsuranceAmount((float) row.getCell(i++).getNumericCellValue()); if (claim.getClaimNumber() != null && claim.getPartyInsurance() != null) { if (!claimDao.checkDupClaimNumber(claim.getClaimNumber())) { claim.setCreateDate(today); claim.setCreateBy(user); claim.setJobDate(today); claim.setJobStatus(JobStatus.RECEIVED); List<TblUserInsurance> tblUserInsurances = userInsuranceDao .searchByInsuranceId(claim.getPartyInsurance().getId()); if (tblUserInsurances != null && !tblUserInsurances.isEmpty()) { claim.setAgent(userDao.findById(tblUserInsurances.get(0).getId().getUserId())); } claimDao.save(claim); claim.setJobNo(DateToolsUtil.convertToString(today, DateToolsUtil.DATE_PATTERN_VIEW_YYYYMMDD, DateToolsUtil.LOCALE_TH) + claim.getId()); claimDao.save(claim); } else { ImportError importError = new ImportError(); importError.setReason(""); importError.setClaimNumber(claim.getClaimNumber()); errorClaimNumbers.add(importError); } } else if (claim.getClaimNumber() != null && claim.getPartyInsurance() == null) { ImportError importError = new ImportError(); importError.setReason("?"); importError.setClaimNumber(claim.getClaimNumber()); errorClaimNumbers.add(importError); } rowAt++; } input.close(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (workbook != null) { try { workbook.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return errorClaimNumbers; }
From source file:com.opendoorlogistics.speedregions.excelshp.io.ExcelWriter.java
License:Apache License
public static void writeSheets(File file, ExportTable... tables) { // create empty workbook with a bold font style XSSFWorkbook wb = new XSSFWorkbook(); XSSFCellStyle headerStyle = wb.createCellStyle(); XSSFFont boldfont = wb.createFont(); boldfont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); boldfont.setFontHeight(12);/*from w w w .j a va 2s .c om*/ headerStyle.setFont(boldfont); // fill workbook for (ExportTable table : tables) { Sheet sheet = wb.createSheet(table.getName()); Row headerRow = sheet.createRow(0); for (int c = 0; c < table.getHeader().size(); c++) { Cell cell = headerRow.createCell(c); cell.setCellStyle(headerStyle); cell.setCellValue(table.getHeader().get(c).getName()); } List<List<String>> rows = table.getRows(); int nr = rows.size(); for (int r = 0; r < nr; r++) { Row row = sheet.createRow(r + 1); List<String> srcRow = rows.get(r); int nc = srcRow.size(); for (int c = 0; c < nc; c++) { //JsonFormatTypes type = table.getColumnType(c); Cell cell = row.createCell(c); String value = srcRow.get(c); writeToCell(value, c < table.getHeader().size() ? table.getHeader().get(c).getFormatType() : JsonFormatTypes.STRING, cell); } } } // try saving FileOutputStream fileOut = null; try { fileOut = new FileOutputStream(file); wb.write(fileOut); } catch (Exception e) { // TODO: handle exception } finally { try { if (fileOut != null) { fileOut.close(); } } catch (Exception e2) { throw new RuntimeException(e2); } try { if (wb != null) { wb.close(); } } catch (Exception e2) { throw new RuntimeException(e2); } } LOGGER.info("Wrote Excel file " + file.getAbsolutePath()); }
From source file:com.philips.his.pixiu.cdr.poi.BigGridDemo.java
License:Apache License
public static void main(String[] args) throws Exception { // Step 1. Create a template file. Setup sheets and workbook-level objects such as // cell styles, number formats, etc. XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet("Big Grid"); Map<String, XSSFCellStyle> styles = createStyles(wb); // name of the zip entry holding sheet data, e.g. /xl/worksheets/sheet1.xml String sheetRef = sheet.getPackagePart().getPartName().getName(); // save the template FileOutputStream os = new FileOutputStream("c:/temp/template.xlsx"); wb.write(os);/*from w w w . j a va 2s .com*/ os.close(); // Step 2. Generate XML file. File tmp = File.createTempFile("sheet", ".xml"); Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), XML_ENCODING); generate(fw, styles); fw.close(); // Step 3. Substitute the template entry with the generated data FileOutputStream out = new FileOutputStream("c:/temp/big-grid.xlsx"); substitute(new File("c:/temp/template.xlsx"), tmp, sheetRef.substring(1), out); out.close(); wb.close(); }
From source file:com.sandstone_tech.lendfastselenium2.util.PoiFileReader.java
/** * Extracts the content of the excel file to be converted as * {@link TestDataModel} object usable by the data provider * /*from ww w .j av a 2 s. c o m*/ * @param fileName * @return */ protected Object[][] readExcelFileAsTDM(String fileName) { try { XSSFWorkbook wb = new XSSFWorkbook(FileUtils.openInputStream(new File(fileName))); // CONFIGURATION // XSSFSheet sheet = wb.getSheetAt(0); // DATA XSSFSheet dataSheet = wb.getSheetAt(1); if (dataSheet != null && dataSheet.getPhysicalNumberOfRows() > 1) { Object[][] testData = new Object[dataSheet.getPhysicalNumberOfRows() - 2][1]; for (int rowCount = 2; rowCount < dataSheet.getPhysicalNumberOfRows(); rowCount++) { XSSFRow row = dataSheet.getRow(rowCount); TestDataModel testDataModel = new TestDataModel(); testDataModel.setUsername(getStringValue(row.getCell(0))); testDataModel.setPassword(getStringValue(row.getCell(1))); testDataModel.setApplicationType(getStringValue(row.getCell(2))); testDataModel.setOrginationFormModel(this.getOrigination(row)); testDataModel.setPersonalDetailsModel(this.getPersonalDetail(row)); testDataModel.setSignedDeclaration(this.getSignedDeclaration(row)); testDataModel.setCurrentAddress(this.getCurrentAddress(row)); testDataModel.setEmploymentDetails(this.getEmploymentDetails(row)); testDataModel.setPreviousEmploymentDetails(this.getPreviousEmploymentDetails(row)); testDataModel.setPurchaseProperty( new PurchaseProperty(this.getPropertyContract(row), this.getPropertyPurpose(row))); testData[rowCount - 2][0] = testDataModel; } wb.close(); return testData; } wb.close(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.siacra.beans.GrupoBean.java
public void archivoXlsx(String path, FileUploadEvent archivo) { excelResponse = new ArrayList<>(); List<Horario> horas = new ArrayList<>(); try {//from w ww.j ava2 s.co m FileInputStream file = new FileInputStream(new File(path + "\\" + archivo.getFile().getFileName())); // Crear el objeto que tendra el libro de Excel XSSFWorkbook workbook = new XSSFWorkbook(file); /* * Obtenemos la primera pestaa a la que se quiera procesar indicando el indice. * Una vez obtenida la hoja excel con las filas que se quieren leer obtenemos el iterator * que nos permite recorrer cada una de las filas que contiene. */ XSSFSheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); Row row; // Recorremos todas las filas para mostrar el contenido de cada celda int cantidad = 0; int cantidad2 = 0; while (rowIterator.hasNext()) { row = rowIterator.next(); if (cantidad2 != 0) { Horario h = new Horario(); UpploadGrupos grupo = new UpploadGrupos(); // Obtenemos el iterator que permite recorres todas las celdas de una fila Iterator<Cell> cellIterator = row.cellIterator(); Cell celda; cantidad = 1; while (cellIterator.hasNext()) { celda = cellIterator.next(); // if((cantidad%10)==0) // { // System.out.print(grupo.toString()); // excelResponse.add(grupo); // grupo = new UpploadGrupos(); // cantidad=1; // } // Dependiendo del formato de la celda el valor se debe mostrar como String, Fecha, boolean, entero... switch (celda.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(celda)) { SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss"); String fecha = f.format(celda.getDateCellValue()); System.out.print(":::::::: " + fecha); Date dos = f.parse(fecha); if (cantidad == 4) { h.setHinicio1(dos); grupo.setInicio1(dos); cantidad++; } else if (cantidad == 5) { h.setHfin1(dos); grupo.setFin1(dos); cantidad++; } else if (cantidad == 7) { h.setHinicio2(dos); grupo.setInicio2(dos); cantidad++; } else if (cantidad == 8) { h.setHfin2(dos); grupo.setFin2(dos); cantidad++; } System.out.println(dos); } // else // { // double numero = celda.getNumericCellValue(); // System.out.println(celda.getNumericCellValue()); // } break; case Cell.CELL_TYPE_STRING: if (cantidad == 1) { grupo.setAsignatura(celda.getStringCellValue()); cantidad++; } else if (cantidad == 2) { grupo.setTipoGrupo(celda.getStringCellValue()); cantidad++; } else if (cantidad == 3) { h.setDia1(celda.getStringCellValue()); grupo.setDia1(celda.getStringCellValue()); cantidad++; } else if (cantidad == 6) { h.setDia2(celda.getStringCellValue()); grupo.setDia2(celda.getStringCellValue()); cantidad++; } else if (cantidad == 9) { grupo.setNumeroGrupo(celda.getStringCellValue()); cantidad++; } else if (cantidad == 10) { grupo.setCupos(celda.getStringCellValue()); cantidad++; } String texto = celda.getStringCellValue(); System.out.println(celda.getStringCellValue()); break; // case Cell.CELL_TYPE_BOOLEAN: // System.out.println(celda.getBooleanCellValue()); // break; }//fin if que obtiene valor de celda } //fin while que recorre celdas System.out.print("objeto:::" + grupo.toString()); System.out.print("objeto:::" + h.toString()); horas.add(h); excelResponse.add(grupo); } // fin if primera iteracion cantidad2++; } // fin while que recorre filas // cerramos el libro excel workbook.close(); } catch (Exception e) { e.printStackTrace(); } procesarListaCargada(); }