List of usage examples for org.apache.poi.ss.usermodel Workbook getSheetAt
Sheet getSheetAt(int index);
From source file:FilesManager.ExcelParser.java
public static List<HardCopy> readExcelData(String fileName) { List<HardCopy> fileList = new ArrayList<>(); try {/*from ww w . j a va 2 s . c om*/ //Create the input stream from the xlsx/xls file FileInputStream fis = new FileInputStream(fileName); //Create Workbook instance for xlsx/xls file input stream Workbook workbook = null; if (fileName.toLowerCase().endsWith("xlsx")) { workbook = new XSSFWorkbook(fis); } else if (fileName.toLowerCase().endsWith("xls")) { workbook = new HSSFWorkbook(fis); } //Get the number of sheets in the xlsx file int numberOfSheets = workbook.getNumberOfSheets(); //loop through each of the sheets for (int i = 0; i < numberOfSheets; i++) { //Get the nth sheet from the workbook Sheet sheet = workbook.getSheetAt(i); //every sheet has rows, iterate over them Iterator<Row> rowIterator = sheet.iterator(); int index = 0; while (rowIterator.hasNext()) { index++; if (index == 1) { rowIterator.next(); continue; } //Get the row object Row row = rowIterator.next(); //Every row has columns, get the column iterator and iterate over them Iterator<Cell> cellIterator = row.cellIterator(); HardCopy f = null; try { List<String> listStrings = new LinkedList<>(); for (int j = 0; j < 6; j++) { Cell c = row.getCell(j); if (c != null) listStrings.add(c.toString()); else listStrings.add(""); } int s = listStrings.size(); f = new HardCopy(listStrings.get(0), listStrings.get(1), listStrings.get(2), listStrings.get(3), (s > 4) ? listStrings.get(4) : "", (s > 5) ? listStrings.get(5) : ""); } catch (Exception e) { e.printStackTrace(); } fileList.add(f); } //end of rows iterator } //end of sheets for loop //close file input stream fis.close(); } catch (IOException e) { e.printStackTrace(); } int k = 1; for (HardCopy file : fileList) { file.key = k++; } return fileList; }
From source file:fr.paris.lutece.plugins.appointment.service.ClosingDayService.java
License:Open Source License
/** * Import the closing dates of a given file * // ww w. j av a2 s. c o m * @param item * the file in input * @return the list of the closing dates in the file * @throws IOException * if error during reading file */ public static List<LocalDate> getImportClosingDays(FileItem item) throws IOException { HashSet<LocalDate> listDays = new HashSet<LocalDate>(); FileInputStream fis = null; Workbook workbook = null; String strExtension = FilenameUtils.getExtension(item.getName()); if (StringUtils.equals(MARK_EXCEL_EXTENSION_XLSX, strExtension)) { try { fis = (FileInputStream) item.getInputStream(); // Using XSSF for xlsx format, for xls use HSSF workbook = new XSSFWorkbook(fis); int numberOfSheets = workbook.getNumberOfSheets(); // looping over each workbook sheet for (int i = 0; i < numberOfSheets; i++) { Sheet sheet = workbook.getSheetAt(i); Iterator<Row> rowIterator = sheet.iterator(); // iterating over each row while (rowIterator.hasNext()) { Row row = (Row) rowIterator.next(); if (row.getRowNum() > 1) { Iterator<Cell> cellIterator = row.cellIterator(); // Iterating over each cell (column wise) in a // particular row. while (cellIterator.hasNext()) { Cell cell = (Cell) cellIterator.next(); // The Cell Containing String will is name. if (cell.getColumnIndex() == 3) { String strdate = StringUtils.EMPTY; if (cell.getCellType() == 0) { Instant instant = cell.getDateCellValue().toInstant(); LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate(); strdate = localDate.format(Utilities.getFormatter()); } if (StringUtils.isNotEmpty(strdate) && strdate.matches(MARK_FORMAT_DATE_REGEX)) { LocalDate date = LocalDate.parse(strdate, Utilities.getFormatter()); listDays.add(date); } } } } } } } finally { if (fis != null) { fis.close(); } if (workbook != null) { workbook.close(); } } } return new ArrayList<LocalDate>(listDays); }
From source file:fr.sc.crator.internal.storage.CRAStorageHandlerImpl.java
License:Open Source License
/** * {@inheritDoc}//from ww w .j a v a 2 s. com * @see fr.sc.crator.storage.CRAStorageHandler#readCRA(fr.sc.crator.model.CRAtor, int, java.lang.String) */ @Override public CRA readCRA(CRAtor crator, int weekNumber, String source) { try { FileInputStream file = new FileInputStream(new File(source)); logger.log(CRAtorLogger.LOG_DEBUG, "Trying to read file " + source); Workbook wb = WorkbookFactory.create(file); file.close(); Sheet sheet = wb.getSheetAt(0); logger.log(CRAtorLogger.LOG_DEBUG, "Instanciating a SpreadCRA"); SpreadCRA cra = CratorFactory.eINSTANCE.createSpreadCRA(); cra.setSheet(sheet); cra.setSource(source); cra.setWeekNumber(weekNumber); CRAWeek week = CratorFactory.eINSTANCE.createCRAWeek(); double workedDay = sheet.getRow(1).getCell(1).getNumericCellValue(); week.setWorkedLoad(workedDay); cra.setWeek(week); logger.log(CRAtorLogger.LOG_DEBUG, "Loading existing data"); loadWeek(crator, cra); return cra; } catch (InvalidFormatException e) { logger.log(CRAtorLogger.LOG_ERROR, "An error occured during loading CRA of " + source + " file. Error: " + e.getMessage()); } catch (IOException e) { logger.log(CRAtorLogger.LOG_ERROR, "An error occured during loading CRA of " + source + " file. Error: " + e.getMessage()); } VoidCRA result = CratorFactory.eINSTANCE.createVoidCRA(); crator.getCras().add(result); return result; }
From source file:github.srlee309.lessWrongBookCreator.excelReader.SummaryFileReader.java
License:Open Source License
private ArrayList<BookSummarySection> getBookSummarySections(Workbook wb) { ArrayList<BookSummarySection> bookSummarySections = new ArrayList<BookSummarySection>(); HashSet<String> bookNames = new HashSet<String>(); HashSet<String> sequenceNames = new HashSet<String>(); Sheet postsSheet = wb.getSheetAt(0); Iterator<Row> rowIterator = postsSheet.iterator(); String currBook = ""; String currSequence = ""; if (rowIterator.hasNext()) { rowIterator.next(); // skip first row with column headers while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); int column = 0; // increment the column we are looking for the value from if the book, sequence or title are not provided column += Math.abs(row.getPhysicalNumberOfCells() - row.getLastCellNum()); PostSummarySection postSummarySection = new PostSummarySection(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); column++;//from w w w . j a va 2s . c om if (cell.getCellType() == Cell.CELL_TYPE_STRING) { switch (column) { case 1: currBook = cell.getStringCellValue(); break; case 2: currSequence = cell.getStringCellValue(); break; case 3: postSummarySection.setTitle(cell.getStringCellValue()); break; case 4: postSummarySection.setUrl(cell.getStringCellValue()); break; case 5: postSummarySection.setSummary(cell.getStringCellValue()); break; } } } if (!bookNames.contains(currBook)) { BookSummarySection bookSummarySection = new BookSummarySection(currBook); bookSummarySections.add(bookSummarySection); bookNames.add(currBook); } if (sequenceNames.contains(currSequence)) { for (BookSummarySection bookSummarySection : bookSummarySections) { SequenceSummarySection sequenceSummarySection = bookSummarySection .getSequenceSummarySection(currSequence); if (sequenceSummarySection != null) { if (!postSummarySection.getUrl().isEmpty()) { sequenceSummarySection.addPostSummarySection(postSummarySection); } } } } else { if (!postSummarySection.getUrl().isEmpty()) { SequenceSummarySection sequenceSummarySection = new SequenceSummarySection(currSequence); sequenceSummarySection.addPostSummarySection(postSummarySection); for (BookSummarySection bookSummarySection : bookSummarySections) { if (bookSummarySection.getTitle().equals(currBook)) { bookSummarySection.addSequenceSummarySection(sequenceSummarySection); } } sequenceNames.add(currSequence); } } } HashMap<String, String> sequenceTitleAndSummaries = new HashMap<String, String>(); HashMap<String, String> bookTitlesAndSummaries = new HashMap<String, String>(); if (wb.getNumberOfSheets() == 1) { logger.info( "There is no second sheet or third sheet found. Therefore, there are no sequence or book summaries found. Perhaps, the excel file is not in the proper format." + newLine); } else if (wb.getNumberOfSheets() == 2) { logger.info( "There is no third sheet found. Therefore, there are no book summaries found. Perhaps, the excel file is not in the proper format." + newLine); sequenceTitleAndSummaries = getTitlesAndSummaries(wb.getSheetAt(1)); } else { sequenceTitleAndSummaries = getTitlesAndSummaries(wb.getSheetAt(1)); bookTitlesAndSummaries = getTitlesAndSummaries(wb.getSheetAt(2)); } for (BookSummarySection bookSummarySection : bookSummarySections) { String bookSummary = bookTitlesAndSummaries.get(bookSummarySection.getTitle()); if (bookSummary != null) { bookSummarySection.setSummary(bookSummary); } for (SequenceSummarySection sequenceSummarySection : bookSummarySection .getSequenceSummarySections()) { String sequenceSummary = sequenceTitleAndSummaries.get(sequenceSummarySection.getTitle()); if (sequenceSummary != null) { sequenceSummarySection.setSummary(sequenceSummary); } } } } else { logger.info( "There were no rows found in the first sheet. Therefore, no posts were found. Perhaps, the excel file is not in the proper format" + newLine); } return bookSummarySections; }
From source file:gov.nih.nci.cananolab.util.ExcelParser.java
License:BSD License
/** * Vertically parse the Excel file into a 2-D matrix represented as a map of map. * Key is Column header, value is a map, whose key is Row header and value is * the cell./* w w w . ja v a2 s. c o m*/ * * @return * @throws IOException */ public SortedMap<String, SortedMap<String, Double>> verticalParse(String fileName) throws IOException { InputStream inputStream = null; SortedMap<String, SortedMap<String, Double>> dataMatrix = new TreeMap<String, SortedMap<String, Double>>(); try { inputStream = new BufferedInputStream(new FileInputStream(fileName)); POIFSFileSystem fs = new POIFSFileSystem(inputStream); Workbook wb = new HSSFWorkbook(fs); Sheet sheet1 = wb.getSheetAt(0); //printSheet(sheet1); Row firstRow = sheet1.getRow(0); int rowIndex = 0; for (Row row : sheet1) { int colIndex = 0; String rowHeader = row.getCell(0).getStringCellValue(); for (Cell cell : row) { if (rowIndex > 0 && colIndex > 0) { //skipping first row/column String columnHeader = firstRow.getCell(colIndex).getStringCellValue(); SortedMap<String, Double> columnData = null; if (dataMatrix.get(columnHeader) != null) { columnData = dataMatrix.get(columnHeader); } else { columnData = new TreeMap<String, Double>(); } if (cell != null) { columnData.put(rowHeader, cell.getNumericCellValue()); dataMatrix.put(columnHeader, columnData); } } colIndex++; } rowIndex++; } } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { } } } return dataMatrix; }
From source file:gov.nih.nci.cananolab.util.ExcelParser.java
License:BSD License
/** * Horizontally parse the Excel file into a 2-D matrix represented as a map of map. * Key is Row header, value is a map, whose key is Column header and value is * the cell./*from w ww .java 2s.com*/ * * @return * @throws IOException */ public SortedMap<String, SortedMap<String, Double>> horizontalParse(String fileName) throws IOException { InputStream inputStream = null; SortedMap<String, SortedMap<String, Double>> dataMatrix = new TreeMap<String, SortedMap<String, Double>>(); try { inputStream = new BufferedInputStream(new FileInputStream(fileName)); POIFSFileSystem fs = new POIFSFileSystem(inputStream); Workbook wb = new HSSFWorkbook(fs); Sheet sheet1 = wb.getSheetAt(0); //printSheet(sheet1); Row firstRow = sheet1.getRow(0); int rowIndex = 0; for (Row row : sheet1) { int colIndex = 0; String rowHeader = row.getCell(0).getStringCellValue(); for (Cell cell : row) { if (rowIndex > 0 && colIndex > 0) { //skipping first row/column String columnHeader = firstRow.getCell(colIndex).getStringCellValue(); SortedMap<String, Double> rowData = null; if (dataMatrix.get(rowHeader) != null) { rowData = dataMatrix.get(rowHeader); } else { rowData = new TreeMap<String, Double>(); } if (cell != null) { rowData.put(columnHeader, cell.getNumericCellValue()); dataMatrix.put(rowHeader, rowData); } } colIndex++; } rowIndex++; } } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { } } } return dataMatrix; }
From source file:gov.nih.nci.cananolab.util.ExcelParser.java
License:BSD License
/** * Parse secondary StanShaw Excel spreadsheet and store data in a 3-layer map. * 1st layer: sample map, key is sample name (261-13-4), value is the 2nd layer map. * 2nd layer: assay map, key is assay name (Aorta 1), value is the 3rd layer map. * 3rd layer: datum map, there are always 3 entries in this map, for example, * key is datum name Median (M), value is 9.02194E-08. * key is datum name Mean (M), value is 7.96025E-08. * key is datum name SEM (M), value is 6.12968E-09. * //from w ww .j a v a 2s .c o m * @param fileName * @return a 3-layer map * @throws IOException */ public SortedMap<String, SortedMap<String, SortedMap<String, Double>>> twoWayParse(String fileName) throws IOException { InputStream inputStream = null; SortedMap<String, SortedMap<String, SortedMap<String, Double>>> dataMatrix = new TreeMap<String, SortedMap<String, SortedMap<String, Double>>>(); try { inputStream = new BufferedInputStream(new FileInputStream(fileName)); POIFSFileSystem fs = new POIFSFileSystem(inputStream); Workbook wb = new HSSFWorkbook(fs); Sheet sheet1 = wb.getSheetAt(0); //printSheet(sheet1); // Sheet must contain >= 2 rows (header + data). if (sheet1.getLastRowNum() < 1) { return dataMatrix; } // Sheet must contain >= 5 columns (assay, sample + 3 datums). Row firstRow = sheet1.getRow(0); if (firstRow.getLastCellNum() < 4) { return dataMatrix; } // Iterate sheet from 2nd row and populate the data matrix. for (int rowIndex = 1; rowIndex <= sheet1.getLastRowNum(); rowIndex++) { Row row = sheet1.getRow(rowIndex); //1.get sampleName key for 1st layer map, assayName key for 2 layer map. String sampleName = row.getCell(1).getStringCellValue(); String assayName = row.getCell(0).getStringCellValue(); //2.find sampleMap in dataMatrix, if null create & store new sampleMap. SortedMap<String, SortedMap<String, Double>> sampleMap = dataMatrix.get(sampleName); if (sampleMap == null) { sampleMap = new TreeMap<String, SortedMap<String, Double>>(); dataMatrix.put(sampleName, sampleMap); } //3.find assayMap in sampleMap, if null create & store new assayMap. SortedMap<String, Double> assayMap = sampleMap.get(assayName); if (assayMap == null) { assayMap = new TreeMap<String, Double>(); sampleMap.put(assayName, assayMap); } //4.iterate row from col-2 to last column, store datum value. for (int colIndex = 2; colIndex <= row.getLastCellNum(); colIndex++) { Cell cell = row.getCell(colIndex); if (cell != null && cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { String datumName = firstRow.getCell(colIndex).getStringCellValue(); assayMap.put(datumName, cell.getNumericCellValue()); } } } } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { } } //this.print2ndMatrix(dataMatrix); } return dataMatrix; }
From source file:gov.nih.nci.evs.app.neopl.XLStoXLSX.java
License:Open Source License
/** * @param args/*from www. jav a2 s . co m*/ * @throws InvalidFormatException * @throws IOException */ public static void run(String inputfile, String outputfile) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(inputfile)); try { Workbook wbIn = new HSSFWorkbook(in); File outFn = new File(outputfile); if (outFn.exists()) { outFn.delete(); } Workbook wbOut = new XSSFWorkbook(); int sheetCnt = wbIn.getNumberOfSheets(); for (int i = 0; i < sheetCnt; i++) { Sheet sIn = wbIn.getSheetAt(0); Sheet sOut = wbOut.createSheet(sIn.getSheetName()); Iterator<Row> rowIt = sIn.rowIterator(); while (rowIt.hasNext()) { Row rowIn = rowIt.next(); Row rowOut = sOut.createRow(rowIn.getRowNum()); Iterator<Cell> cellIt = rowIn.cellIterator(); while (cellIt.hasNext()) { Cell cellIn = cellIt.next(); Cell cellOut = rowOut.createCell(cellIn.getColumnIndex(), cellIn.getCellType()); switch (cellIn.getCellType()) { case Cell.CELL_TYPE_BLANK: break; case Cell.CELL_TYPE_BOOLEAN: cellOut.setCellValue(cellIn.getBooleanCellValue()); break; case Cell.CELL_TYPE_ERROR: cellOut.setCellValue(cellIn.getErrorCellValue()); break; case Cell.CELL_TYPE_FORMULA: cellOut.setCellFormula(cellIn.getCellFormula()); break; case Cell.CELL_TYPE_NUMERIC: cellOut.setCellValue(cellIn.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: cellOut.setCellValue(cellIn.getStringCellValue()); break; } { CellStyle styleIn = cellIn.getCellStyle(); CellStyle styleOut = cellOut.getCellStyle(); styleOut.setDataFormat(styleIn.getDataFormat()); } cellOut.setCellComment(cellIn.getCellComment()); // HSSFCellStyle cannot be cast to XSSFCellStyle // cellOut.setCellStyle(cellIn.getCellStyle()); } } } OutputStream out = new BufferedOutputStream(new FileOutputStream(outFn)); try { wbOut.write(out); } finally { out.close(); } } finally { in.close(); } }
From source file:gov.nih.nci.evs.app.neopl.XLSXMetadataUtils.java
License:Open Source License
public static boolean freezeRow(String filename, int sheetNumber, int rowNum) { FileOutputStream fileOut = null; boolean status = false; try {//from w ww. j a v a 2 s .c om InputStream inp = new FileInputStream(filename); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(sheetNumber); sheet.createFreezePane(0, rowNum); // this will freeze first rowNum rows fileOut = new FileOutputStream(filename); wb.write(fileOut); status = true; System.out.println("File modified " + filename); } catch (Exception ex) { //ex.printStackTrace(); System.out.println("ERROR: freezeRow " + filename); } finally { try { fileOut.close(); } catch (Exception ex) { ex.printStackTrace(); } } return status; }
From source file:gov.nij.er.ui.EntityResolutionDemo.java
License:Apache License
private void loadExcelData(File file) throws Exception { LOG.debug("Loading Excel data file " + file.getAbsolutePath()); InputStream inp = new FileInputStream(file); Workbook wb = WorkbookFactory.create(inp); // note that we read all the data out of the spreadsheet first, then // update the models. this way if there is // an error, we don't wipe out what the user already has. Sheet sheet = wb.getSheetAt(0); Row parametersRow = sheet.getRow(0); List<String> parameterNames = new ArrayList<String>(); for (Cell cell : parametersRow) { String v = cell.getStringCellValue(); if (parameterNames.contains(v)) { error("Duplicate field: " + v); return; }//from w ww . j a v a 2s . c o m parameterNames.add(v); LOG.debug("Adding parameter " + v); } int parameterCount = parameterNames.size(); LOG.debug("Excel loading read " + parameterCount + " parameters"); List<ExternallyIdentifiableRecord> records = new ArrayList<ExternallyIdentifiableRecord>(); int rowCount = sheet.getLastRowNum(); LOG.debug("Loading " + (rowCount - 1) + " rows from " + sheet.getSheetName()); int digits = (int) (Math.floor(Math.log10(rowCount)) + 1); DataFormatter dataFormatter = new DataFormatter(); for (int rowIndex = 1; rowIndex <= rowCount; rowIndex++) { List<Attribute> attributes = new ArrayList<Attribute>(parameterCount); Row row = sheet.getRow(rowIndex); for (int i = 0; i < parameterCount; i++) { Cell cell = row.getCell(i); String v = dataFormatter.formatCellValue(cell); String parameterName = parameterNames.get(attributes.size()); attributes.add(new Attribute(parameterName, v)); // LOG.debug("Adding attribute, name=" + parameterName + ", v=" // + (v==null ? "null" : "'" + v + "'")); } records.add(new ExternallyIdentifiableRecord(makeAttributes(attributes.toArray(new Attribute[] {})), String.format("%0" + digits + "d", rowIndex))); } LOG.debug("Read " + records.size() + " records from Excel"); List<RecordWrapper> recordWrappers = EntityResolutionConversionUtils.convertRecords(records); rawDataTreeModel.init(recordWrappers); parametersTableModel.clear(); parametersTableModel.addParameters(parameterNames); }