public static List<String[]> readExcel(InputStream is, int sheetIndex) throws Exception { Workbook workbook = WorkbookFactory.create(is); Sheet sheet = workbook.getSheetAt(sheetIndex); List<String[]> data = new ArrayList<>(); for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); if (row == null) continue; int last = row.getLastCellNum(); String[] rowData = new String[last]; for (int j = 0; j < last; j++) { Cell cell = row.getCell(j); rowData[j] = cell == null ? null : getCellString(cell); } data.add(rowData); } return data; }
/** * テスト用のシートの取得 * <p>修正したりするためのシート */ private List<Sheet> loadSheetForTest(final File file) throws InvalidFormatException, IOException { List<Sheet> list = new ArrayList<>(); try(InputStream in = new FileInputStream(file)) { Workbook workbook = WorkbookFactory.create(in); final int sheetNum = workbook.getNumberOfSheets(); for(int i=0; i < sheetNum; i++) { final Sheet sheet = workbook.getSheetAt(i); final String sheetName = sheet.getSheetName(); if(!sheetName.startsWith("テスト")) { continue; } list.add(sheet); } } return list; }
@Override protected void fillTrie(Logger logger, Trie<List<String>> trie, Corpus corpus) throws IOException, ModuleException { Iterator<InputStream> inputStreams = xlsFile.getInputStreams(); while (inputStreams.hasNext()) { try (InputStream is = inputStreams.next()) { Workbook wb = WorkbookFactory.create(is); for (int sheetNumber : sheets) { Sheet sheet = wb.getSheetAt(sheetNumber); fillSheetEntries(trie, sheet); } } catch (EncryptedDocumentException|InvalidFormatException e) { rethrow(e); } } }
public static void readWorkBook() throws Exception { // poi��ȡexcel // ����Ҫ������ļ��������� final InputStream inp = new FileInputStream("d:\\workbooks.xlsx"); // �������������������� �������������� final Workbook wb = WorkbookFactory.create(inp); for (final Sheet sheet : wb) { System.out.println(sheet.getSheetName()); for (final Row row : sheet) { for (final Cell cell : row) { System.out.print(cell.toString() + " "); } System.out.println(); } } // �ر������� inp.close(); }
public static CombinationSolver<String, String> importCombination(File file) throws Exception { if (file.getName().endsWith(".csv")) { try (Reader reader = new FileReader(file); TableCSVReader csvReader = new TableCSVReader(reader)) { csvReader.setUseHeader(true); return importCombination(csvReader); } } else if (file.getName().endsWith(".xls") || file.getName().endsWith(".xlsx")) { Workbook workbook = WorkbookFactory.create(file); Sheet sheet = workbook.getSheetAt(0); try (ExcelSheetReader sheetReader = new ExcelSheetReader(sheet)) { sheetReader.setUseHeader(true); return importCombination(sheetReader); } } else { throw new IllegalArgumentException("Unsupported file"); } }
public static boolean needsNewTracker() throws Exception { final String FILE = workbook.getAbsolutePath(); InputStream inp = new FileInputStream(FILE); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); Row row = sheet.getRow(1); Cell cell = row.getCell(1); Date firstCellContents = cell.getDateCellValue(); Calendar firstDayCalendar = Calendar.getInstance(); firstDayCalendar.setTime(firstCellContents); int diff = daysBetweenFirstPST(firstDayCalendar); if (diff < 14) { return false; } else { return true; } }
public static List<String[]> readExecl(InputStream is, int column) throws Exception { // InputStream is = new FileInputStream(path); // Workbook xssfWorkbook = new XSSFWorkbook(is);//初始化失败,暂时不解析excel2010 Workbook workbook = WorkbookFactory.create(is); List<String[]> list = new ArrayList<String[]>(); for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) { Sheet sheet = workbook.getSheetAt(numSheet); if (sheet == null || sheet.getLastRowNum() <= 0) { continue; } for(int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { Row xssfRow = sheet.getRow(rowNum); if (xssfRow != null) { String[] dataRow = new String[column]; for (int i = 0; i < column; i++) { Cell ic_no = xssfRow.getCell(i); dataRow[i] = getCellValue(ic_no); } list.add(dataRow); } } } return list; }
/** * Get Workbook * * @param completeFilePath * @param fileExtension * @return workbook * @throws ParserException */ private Workbook getWorkbook(File completeFilePath, String fileExtension) throws ParserException { /* Open & Read File */ try (FileInputStream inputStream = new FileInputStream(completeFilePath)) { /* Get Type Based On File Extension */ return fileExtension.equals(Constants.EXT_XLSX) ? (XSSFWorkbook) WorkbookFactory .create(inputStream) : fileExtension .equals(Constants.EXT_XLS) ? (HSSFWorkbook) WorkbookFactory .create(inputStream) : null; } catch (Exception ex) { /* Catch, Log & Throw Exception */ LOGGER.error("Error Occured While Parsing File!", ex); throw new ParserException(exceptionFactory.create( ExceptionType.PARSER, "PAR003", completeFilePath.getAbsolutePath()), ex); } }
@Override public void scan(File file, String filename, SheetSelection selection, IExcelImportFileVisitor<Workbook, Sheet, Row, Cell, CellReference> visitor) throws TableImportException { Validate.notNull(file, "file must not be null"); Validate.notNull(visitor, "visitor must not be null"); ApachePoiImportNavigator navigator = new ApachePoiImportNavigator(filename); try (InputStream stream = new TFileInputStream(file)) { Workbook workbook = WorkbookFactory.create(stream); for (int index = 0 ; index < workbook.getNumberOfSheets() ; ++index) { Sheet sheet = workbook.getSheetAt(index); if (navigator.tableHasContent(sheet) && SELECTIONS_PREDICATES.get(selection).apply(sheet)) { visitor.visitSheet(navigator, workbook, sheet); } } } catch (InvalidFormatException | IOException | IllegalArgumentException e) { throw new TableImportFileException(e, navigator.getLocation(null, null, null)); } }
@Override public void scan(InputStream stream, String filename, SheetSelection selection, IExcelImportFileVisitor<Workbook, Sheet, Row, Cell, CellReference> visitor) throws TableImportException { Validate.notNull(stream, "stream must not be null"); Validate.notNull(visitor, "visitor must not be null"); ApachePoiImportNavigator navigator = new ApachePoiImportNavigator(filename); try { Workbook workbook = WorkbookFactory.create(stream); for (int index = 0 ; index < workbook.getNumberOfSheets() ; ++index) { Sheet sheet = workbook.getSheetAt(index); if (navigator.tableHasContent(sheet) && SELECTIONS_PREDICATES.get(selection).apply(sheet)) { visitor.visitSheet(navigator, workbook, sheet); } } } catch (InvalidFormatException | IOException | IllegalArgumentException e) { throw new TableImportFileException(e, navigator.getLocation(null, null, null)); } }
/** * 書式確認用のシートの取得 * @param file * @return * @throws InvalidFormatException * @throws IOException */ private List<Sheet> loadSheetForFormat(final File file) throws InvalidFormatException, IOException { List<Sheet> list = new ArrayList<>(); try(InputStream in = new FileInputStream(file)) { Workbook workbook = WorkbookFactory.create(in); final int sheetNum = workbook.getNumberOfSheets(); for(int i=0; i < sheetNum; i++) { final Sheet sheet = workbook.getSheetAt(i); final String sheetName = sheet.getSheetName(); if(!sheetName.startsWith("書式")) { continue; } list.add(sheet); } } return list; }
/** * シート名を指定して取得する * @param file * @param name */ private Sheet loadSheetByName(final File file, final String name) throws InvalidFormatException, IOException { try(InputStream in = new FileInputStream(file)) { Workbook workbook = WorkbookFactory.create(in); final int sheetNum = workbook.getNumberOfSheets(); for(int i=0; i < sheetNum; i++) { final Sheet sheet = workbook.getSheetAt(i); final String sheetName = sheet.getSheetName(); if(sheetName.equals(name)) { return sheet; } } } throw new IllegalStateException("not found sheet : " + name); }
private Workbook generateWorkbookWithSheets(ReportConfig reportConfig) throws IOException, InvalidFormatException { if (!reportConfig.isAppendToDestination()) { LOGGER.debug("creating empty workbook with sheets"); Workbook workbook = new XSSFWorkbook(); FileOutputStream fileOut = new FileOutputStream(reportConfig.getDestinationFile()); generateSheets(reportConfig, workbook); workbook.write(fileOut); fileOut.close(); LOGGER.debug("workbook created"); return workbook; } else { LOGGER.debug("will append to destination file"); File destFile = new File(reportConfig.getDestinationFile()); FileInputStream fileInputStream = new FileInputStream(destFile); OPCPackage opc = OPCPackage.open(fileInputStream); return WorkbookFactory.create(opc); } }
@org.junit.Test public void poiParserMultipleSheets() throws Exception { //generate SheetParser parser = new PoiSheetParser(); parser.load(getClass().getResourceAsStream("expressions-multiple-sheets.xlsx")); parser.process(new MVEL2Interpreter(), new User("Silva"), null, null); ByteArrayOutputStream bos = new ByteArrayOutputStream(); parser.writeTo(bos); //check Workbook wb = WorkbookFactory.create(new ByteArrayInputStream(bos.toByteArray())); assertEquals("Name: Silva", wb.getSheetAt(0).getRow(2).getCell(1).getStringCellValue()); assertEquals("Address: Endere�o", wb.getSheetAt(1).getRow(2).getCell(1).getStringCellValue()); }
@org.junit.Test public void poiParserLoopEmpty() throws Exception { //model Map<String, Object> variables = new HashMap<String, Object>(); List<Parcel> parcels = new ArrayList<Parcel>(); variables.put("parcels", parcels); variables.put("client", new User("Silva")); //generate SheetParser parser = new PoiSheetParser(); parser.load(getClass().getResourceAsStream("loop-rows-empty.xlsx")); parser.process(new MVEL2Interpreter(), null, variables, null); ByteArrayOutputStream bos = new ByteArrayOutputStream(); parser.writeTo(bos); //check Workbook wb = WorkbookFactory.create(new ByteArrayInputStream(bos.toByteArray())); //wb.write(new FileOutputStream("target/loop-rows-empty-output.xlsx")); assertEquals("Silva", wb.getSheetAt(0).getRow(1).getCell(2).getStringCellValue()); assertEquals(6, wb.getSheetAt(0).getLastRowNum()); assertEquals("A", wb.getSheetAt(0).getRow(5).getCell(0).getStringCellValue()); assertEquals("B", wb.getSheetAt(0).getRow(6).getCell(0).getStringCellValue()); }
public static void main(String[] args) throws Exception { String dataPath = "src/featurescomparison/workingwithcellsrowscolumns/hideunhidecells/data/"; InputStream inStream = new FileInputStream(dataPath + "workbook.xls"); Workbook workbook = WorkbookFactory.create(inStream); Sheet sheet = workbook.createSheet(); Row row = sheet.createRow(0); row.setZeroHeight(true); FileOutputStream fileOut = new FileOutputStream(dataPath + "hideUnhideCells_Apache_Out.xls"); workbook.write(fileOut); fileOut.close(); System.out.println("Process Completed."); }
public static void main(String[] args) throws Exception { String dataPath = "src/featurescomparison/workingwithcellsrowscolumns/autofitrowandcolumn/data/"; InputStream inStream = new FileInputStream(dataPath + "workbook.xls"); Workbook workbook = WorkbookFactory.create(inStream); Sheet sheet = workbook.createSheet("new sheet"); sheet.autoSizeColumn(0); //adjust width of the first column sheet.autoSizeColumn(1); //adjust width of the second column FileOutputStream fileOut; fileOut = new FileOutputStream(dataPath + "AutoFit_Apache_Out.xls"); workbook.write(fileOut); fileOut.close(); System.out.println("Process Completed."); }
@Test public void testDownloadXlsNoHeader() throws InvalidFormatException, IOException { // 準備 MockHttpServletResponse response = new MockHttpServletResponse(); // 実行 tableDownloadOperation.downloadXls(response, "test_{0}.xls", new LocalDateTime(2015, 1, 23, 12, 34, 56), null, createCommonClause(), createOrderByClause(), constant("TEST00")); // 検証 assertEquals("application/vnd.ms-excel", response.getContentType()); assertEquals("application/vnd.ms-excel", response.getHeader("Content-Type")); assertEquals("attachment; filename=\"test_20150123123456.xls\"", response.getHeader("Content-Disposition")); try (InputStream in = new ByteArrayInputStream(response.getContentAsByteArray()); Workbook workbook = WorkbookFactory.create(in); ExcelReader reader = new ExcelReader(workbook)) { String[] record; record = reader.read(); assertEquals(1, record.length); assertEquals("TEST00", record[0]); assertNull(reader.read()); } }
@Test public void testDownloadXlsWithHeader() throws InvalidFormatException, IOException { // 準備 MockHttpServletResponse response = new MockHttpServletResponse(); // 実行 tableDownloadOperation.downloadXls(response, "test_{0}.xls", new LocalDateTime(2015, 1, 23, 12, 34, 56), asList("HEAD0"), createCommonClause(), createOrderByClause(), constant("TEST00")); // 検証 assertEquals("application/vnd.ms-excel", response.getContentType()); assertEquals("application/vnd.ms-excel", response.getHeader("Content-Type")); assertEquals("attachment; filename=\"test_20150123123456.xls\"", response.getHeader("Content-Disposition")); try (InputStream in = new ByteArrayInputStream(response.getContentAsByteArray()); Workbook workbook = WorkbookFactory.create(in); ExcelReader reader = new ExcelReader(workbook)) { String[] record; record = reader.read(); assertEquals(1, record.length); assertEquals("HEAD0", record[0]); record = reader.read(); assertEquals(1, record.length); assertEquals("TEST00", record[0]); assertNull(reader.read()); } }
@Test public void testDownloadXlsxNoHeader() throws InvalidFormatException, IOException { // 準備 MockHttpServletResponse response = new MockHttpServletResponse(); // 実行 tableDownloadOperation.downloadXlsx(response, "test_{0}.xlsx", new LocalDateTime(2015, 1, 23, 12, 34, 56), null, createCommonClause(), createOrderByClause(), constant("TEST00")); // 検証 assertEquals("application/vnd.ms-excel", response.getContentType()); assertEquals("application/vnd.ms-excel", response.getHeader("Content-Type")); assertEquals("attachment; filename=\"test_20150123123456.xlsx\"", response.getHeader("Content-Disposition")); try (InputStream in = new ByteArrayInputStream(response.getContentAsByteArray()); Workbook workbook = WorkbookFactory.create(in); ExcelReader reader = new ExcelReader(workbook)) { String[] record; record = reader.read(); assertEquals(1, record.length); assertEquals("TEST00", record[0]); assertNull(reader.read()); } }
@Override public void parse(File inFile) throws DPUException, ParseFailed { final Workbook wb; try { wb = WorkbookFactory.create(inFile); } catch (IOException | InvalidFormatException ex) { throw new ParseFailed("WorkbookFactory creation failed.", ex); } // get sheet to process final List<Integer> toProcess = new LinkedList<>(); for (Integer index = 0; index < wb.getNumberOfSheets(); ++index) { if (config.sheetName == null || config.sheetName.compareTo(wb.getSheetName(index)) == 0) { // add toProcess.add(index); } } // // process selected sheets // for (Integer sheetIndex : toProcess) { if (context.canceled()) { break; } parseSheet(wb, sheetIndex); } }
@Test public void saveTest_HeadersOnly() throws InvalidFormatException, IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // save it Ssio.save(ITRecord.getHeaderMap(), null, outputStream); byte[] spreadsheet = outputStream.toByteArray(); // do a save for human eye check FileUtils.writeByteArrayToFile(createFile("saveTest_HeadersOnly"), spreadsheet); // then parse it Workbook workbook = WorkbookFactory.create(new ByteArrayInputStream(spreadsheet)); /*** do assertions ***/ Sheet sheet = workbook.getSheetAt(0); Row headerRow = sheet.getRow(0); // size Assert.assertEquals(0, sheet.getLastRowNum()); Assert.assertEquals(ITRecord.getHeaderMap().size(), headerRow.getLastCellNum()); }
@Test public void testDownloadXlsNoHeader() throws InvalidFormatException, IOException { // 準備 MockHttpServletResponse response = new MockHttpServletResponse(); // 実行 tableDownloadOperation.downloadXls(response, "test_{0}.xls", new LocalDateTime(2015, 1, 23, 12, 34, 56), null, createCommonClause(), createOrderByClause(), constant("TEST00")); // 検証 assertEquals("application/vnd.ms-excel", response.getContentType()); assertEquals("application/vnd.ms-excel", response.getHeader("Content-Type")); assertEquals("attachment; filename=\"test_20150123123456.xls\"; filename*=UTF-8''test_20150123123456.xls", response.getHeader("Content-Disposition")); try (InputStream in = new ByteArrayInputStream(response.getContentAsByteArray()); Workbook workbook = WorkbookFactory.create(in); ExcelReader reader = new ExcelReader(workbook)) { String[] record; record = reader.read(); assertEquals(1, record.length); assertEquals("TEST00", record[0]); assertNull(reader.read()); } }
@Test public void testDownloadXlsWithHeader() throws InvalidFormatException, IOException { // 準備 MockHttpServletResponse response = new MockHttpServletResponse(); // 実行 tableDownloadOperation.downloadXls(response, "test_{0}.xls", new LocalDateTime(2015, 1, 23, 12, 34, 56), asList("HEAD0"), createCommonClause(), createOrderByClause(), constant("TEST00")); // 検証 assertEquals("application/vnd.ms-excel", response.getContentType()); assertEquals("application/vnd.ms-excel", response.getHeader("Content-Type")); assertEquals("attachment; filename=\"test_20150123123456.xls\"; filename*=UTF-8''test_20150123123456.xls", response.getHeader("Content-Disposition")); try (InputStream in = new ByteArrayInputStream(response.getContentAsByteArray()); Workbook workbook = WorkbookFactory.create(in); ExcelReader reader = new ExcelReader(workbook)) { String[] record; record = reader.read(); assertEquals(1, record.length); assertEquals("HEAD0", record[0]); record = reader.read(); assertEquals(1, record.length); assertEquals("TEST00", record[0]); assertNull(reader.read()); } }
@Test public void testDownloadXlsxNoHeader() throws InvalidFormatException, IOException { // 準備 MockHttpServletResponse response = new MockHttpServletResponse(); // 実行 tableDownloadOperation.downloadXlsx(response, "test_{0}.xlsx", new LocalDateTime(2015, 1, 23, 12, 34, 56), null, createCommonClause(), createOrderByClause(), constant("TEST00")); // 検証 assertEquals("application/vnd.ms-excel", response.getContentType()); assertEquals("application/vnd.ms-excel", response.getHeader("Content-Type")); assertEquals("attachment; filename=\"test_20150123123456.xlsx\"; filename*=UTF-8''test_20150123123456.xlsx", response.getHeader("Content-Disposition")); try (InputStream in = new ByteArrayInputStream(response.getContentAsByteArray()); Workbook workbook = WorkbookFactory.create(in); ExcelReader reader = new ExcelReader(workbook)) { String[] record; record = reader.read(); assertEquals(1, record.length); assertEquals("TEST00", record[0]); assertNull(reader.read()); } }
@Test public void testDoConvert() throws Exception { Path temporaryOutput = Files.createTempFile("excel2csv", ".xlsx"); Converter.builder().copyAllSheets(true).build().doConvert(Arrays.asList( new File(temporaryDirectory.toFile(), "CO2.csv"), new File(temporaryDirectory.toFile(), "DNase.csv"), new File(temporaryDirectory.toFile(), "iris.csv") ), temporaryOutput.toFile()); Workbook workbook = WorkbookFactory.create(temporaryOutput.toFile()); for (String one : new String[]{"iris", "CO2", "DNase"}) { try (TableReader reader = new ExcelSheetReader(workbook.getSheet(one + ".csv"))) { Excel2CSVTest.assertObjects(reference.get(one), reader.readAll()); } } }
@Test public void testDoConvert2() throws Exception { Path temporaryOutput = Files.createTempFile("excel2csv", ".xlsx"); Converter.builder().copyAllSheets(true).build().doConvert(Arrays.asList( new File(temporaryDirectory.toFile(), "multisheet.xls"), new File(temporaryDirectory.toFile(), "multisheet.xlsx") ), temporaryOutput.toFile()); Workbook workbook = WorkbookFactory.create(temporaryOutput.toFile()); for (String one : new String[]{"iris", "CO2", "DNase"}) { for (String suffix : new String[]{"", "-1"}) { try (TableReader reader = new ExcelSheetReader(workbook.getSheet(one+suffix))) { Excel2CSVTest.assertObjects(reference.get(one), reader.readAll()); } } } }
@Test public void testDoConvert4() throws Exception { Path temporaryOutput = Files.createTempFile("excel2csv", ".xlsx"); Converter.builder().copyAllSheets(false).outputSheetName("iris").build().doConvert(Collections.singletonList( new File(temporaryDirectory.toFile(), "multisheet.xls") ), temporaryOutput.toFile()); Workbook workbook = WorkbookFactory.create(temporaryOutput.toFile()); Assert.assertEquals(1, workbook.getNumberOfSheets()); for (String one : new String[]{"iris"}) { log.info("Sheet name: {}", workbook.getSheetName(0)); try (TableReader reader = new ExcelSheetReader(workbook.getSheet(one))) { Excel2CSVTest.assertObjects(reference.get(one), reader.readAll()); } } }
/** * Transforms the template Excel spreadsheet represented by the given input * filename. Applies the given <code>Map</code> of beans to all sheets. * Writes the resultant Excel spreadsheet to the given output filename. * @param inFilename The template spreadsheet filename. * @param outFilename The resultant spreadsheet filename. * @param beans The <code>Map</code> of bean names to bean objects. * @throws IOException If there is a problem reading or writing any Excel * spreadsheet. * @throws InvalidFormatException If there is a problem creating a * <code>Workbook</code> object. * @since 0.2.0 */ public void transform(String inFilename, String outFilename, Map<String, Object> beans) throws IOException, InvalidFormatException { FileOutputStream fileOut = null; try { fileOut = new FileOutputStream(outFilename); Workbook workbook = WorkbookFactory.create(new File(inFilename)); transform(workbook, beans); workbook.write(fileOut); } finally { if (fileOut != null) try { fileOut.close(); } catch (IOException ignored) {} } }
private Workbook open(File f) throws IOException { try { return WorkbookFactory.create(f); } catch (InvalidFormatException e) { throw new IOException("File broken", e); } }
private Workbook open(ContentReader reader) throws IOException { // If we can use a FileChannel, do if (reader.getMimetype().equals(MimetypeMap.MIMETYPE_EXCEL)) { NPOIFSFileSystem fs = new NPOIFSFileSystem(reader.getFileChannel()); return WorkbookFactory.create(fs); } // Otherwise, ContentReader doesn't offer a File // So, we have to go via the InputStream try { return WorkbookFactory.create(reader.getContentInputStream()); } catch (InvalidFormatException e) { throw new IOException("File broken", e); } }
private Map<String, List<List<String>>> readExcel(File tmpFile) throws IOException, InvalidFormatException { Map<String, List<List<String>>> actual = newHashMap(); try (Workbook workbook = WorkbookFactory.create(tmpFile)) { List<List<String>> sheetResult = newArrayList(); for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) { Sheet sheet = workbook.getSheetAt(sheetNum); for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) { List<String> rowResult = newArrayList(); Row row = sheet.getRow(rowNum); for (int colNum = 0; colNum < row.getLastCellNum(); colNum++) { rowResult.add(row.getCell(colNum, CREATE_NULL_AS_BLANK).getStringCellValue()); } sheetResult.add(rowResult); } actual.put(sheet.getSheetName(), sheetResult); } } return actual; }
@Override public List<Sheet> buildExcelSheetsFromFile(File file) throws IOException, InvalidFormatException, EmptySheetException { List<Sheet> sheets = newArrayList(); try (Workbook workbook = WorkbookFactory.create(file)) { int numberOfSheets = workbook.getNumberOfSheets(); for (int index = 0; index < numberOfSheets; index++) { Sheet sheet = workbook.getSheetAt(index); if (sheet.getPhysicalNumberOfRows() == 0) { throw new EmptySheetException("Sheet [" + sheet.getSheetName() + "] is empty"); } else if (sheet.getPhysicalNumberOfRows() == 1) { throw new MolgenisDataException( "Header was found, but no data is present in sheet [" + sheet.getSheetName() + "]"); } else { sheets.add(sheet); } } } catch (IOException | InvalidFormatException | EncryptedDocumentException ex) { LOG.error(ex.getLocalizedMessage()); throw new MolgenisDataException("Could not create excel workbook from file"); } return sheets; }
public ExcelRepositoryCollection(String name, InputStream in, CellProcessor... cellProcessors) throws IOException, MolgenisInvalidFormatException { super(ExcelFileExtensions.getExcel(), cellProcessors); this.name = name; try { workbook = WorkbookFactory.create(in); } catch (InvalidFormatException e) { throw new MolgenisInvalidFormatException(e.getMessage()); } }
@BeforeMethod public void beforeMethod() throws InvalidFormatException, IOException { is = getClass().getResourceAsStream("/test.xls"); workbook = WorkbookFactory.create(is); excelSheetReader = new ExcelRepository("test.xls", workbook.getSheet("test"), entityTypeFactory, attrMetaFactory); }
@Override public void run() { log.trace("import file {}", xlsFile); try (FileInputStream fis = new FileInputStream(xlsFile)) { Workbook workbook = WorkbookFactory.create(fis); Process process = new Process(); ProcessDocumentation doc = new ProcessDocumentation(); process.setDocumentation(doc); Config config = new Config(workbook, database, process); readSheets(config); ProcessDao dao = new ProcessDao(database); dao.insert(process); } catch (Exception e) { log.error("failed to import file " + xlsFile, e); } }
private static Workbook read(File file, boolean ifWrap) throws InvalidFormatException, IOException { Args.notNull(file, "file"); try { return WorkbookFactory.create(file); } catch (InvalidFormatException e) { if (!ifWrap || !JxlUtils.canWrap()) { throw e; } Logger.getAnonymousLogger().log(Level.INFO, "can not create Workbook from File, using poi", e); // rarely, it may be possible to read through JXL. return WorkbookFactory.create(JxlUtils.wrap(file)); } }
public void testHasNext() throws Exception { Workbook workbook = WorkbookFactory.create(new FileInputStream( "src/test/resources/xls_single_cell_sheet.xls")); Sheet sheet = workbook.getSheetAt(0); // POI's row numbers are 0-based also - the last cell in the sheet is // actually A6. assertEquals(5, sheet.getLastRowNum()); ZeroBasedRowIterator it = new ZeroBasedRowIterator(sheet); assertTrue(it.hasNext()); assertNull(it.next()); assertTrue(it.hasNext()); assertNull(it.next()); assertTrue(it.hasNext()); assertNull(it.next()); assertTrue(it.hasNext()); assertNull(it.next()); assertTrue(it.hasNext()); assertNull(it.next()); assertTrue(it.hasNext()); assertNotNull(it.next()); assertFalse(it.hasNext()); }
@Test public void testExcelConversion() throws IOException { PdfToExcelParameters params = getParams(); execute(params); testContext.assertTaskCompleted(); testContext.assertOutputSize(1).assertOutputContainsFilenames("tabular-data.xlsx").forEachRawOutput(p -> { try { InputStream in = new FileInputStream(p.toFile()); Workbook wb = WorkbookFactory.create(in); assertThat(wb.getNumberOfSheets(), is(2)); Sheet sheet = wb.getSheetAt(0); assertThat(sheet.getPhysicalNumberOfRows(), is(37)); assertThat(sheet.getSheetName(), is("Table 1 (Page 1)")); assertThat(getDataRow(sheet, 0), is(Arrays.asList("OrderDate", "Region", "Rep", "Item", "Units", "Unit Cost", "Total"))); assertThat(getDataRow(sheet, 10), is(Arrays.asList("6/8/15", "East", "Jones", "Binder", "60", "8.99", "539.40"))); assertThat(getDataRow(sheet, 13), is(Arrays.asList("7/29/15", "East", "Parent", "Binder", "81", "19.99", "1,619.19"))); } catch (Exception e) { throw new RuntimeException(e); } }); }
public XLSEntityIterator(String uri, Converter<String, ?> preprocessor, ComplexTypeDescriptor entityDescriptor, String sheetName, boolean formatted) throws IOException, InvalidFormatException { this.uri = uri; this.preprocessor = preprocessor; this.entityDescriptor = entityDescriptor; this.rowBased = (entityDescriptor != null && entityDescriptor.isRowBased() != null ? entityDescriptor.isRowBased() : true); this.emptyMarker = (entityDescriptor != null && entityDescriptor.getEmptyMarker() != null ? entityDescriptor.getEmptyMarker() : null); this.workbook = WorkbookFactory.create(IOUtil.getInputStreamForURI(uri)); this.sheetName = sheetName; this.sheetNo = -1; this.formatted = formatted; }