Example usage for org.apache.poi.ss.usermodel Workbook getNumberOfSheets

List of usage examples for org.apache.poi.ss.usermodel Workbook getNumberOfSheets

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Workbook getNumberOfSheets.

Prototype

int getNumberOfSheets();

Source Link

Document

Get the number of spreadsheets in the workbook

Usage

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   www.j  a  v a 2s.  c o m
                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.evs.app.neopl.XLStoXLSX.java

License:Open Source License

/**
 * @param args//  ww  w.ja v a2 s .c  o  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.va.isaac.request.uscrs.USCRSBatchTemplate.java

License:Apache License

/**
 * Generate the enums and constants from a template file for use at the top of this class
 *//* w w w .  j a va2  s. com*/
public static void main(String[] args) throws IOException {
    //USCRSBatchTemplate b = new USCRSBatchTemplate(USCRSBatchTemplate.class.getResourceAsStream("/USCRS_Batch_Template-2015-01-27.xls"));

    Workbook wb = new HSSFWorkbook(
            USCRSBatchTemplate.class.getResourceAsStream("/USCRS_Batch_Template-2015-01-27.xls"));

    ArrayList<String> sheets = new ArrayList<>();
    HashSet<String> columns = new HashSet<>();

    LinkedHashMap<String, ArrayList<String>> pickLists = new LinkedHashMap<>();

    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        Sheet sheet = wb.getSheetAt(i);
        String sheetName = sheet.getSheetName();
        sheets.add(sheetName);
        if (sheetName.equals("Help")) {
            continue;
        }

        sheet.getRow(0).forEach(headerCell -> {
            if (sheetName.equals("metadata") && headerCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                //SKIP - the metadata tab has a cell that is just a number - likely the release date
            } else {
                String stringValue = toString(headerCell);
                columns.add(stringValue);
                if (sheetName.equals("metadata")) {
                    pickLists.put(stringValue, new ArrayList<>());
                    for (int row = 1; row < sheet.getLastRowNum(); row++) {
                        Cell valueCell = sheet.getRow(row).getCell(headerCell.getColumnIndex());
                        if (valueCell != null) {
                            String s = toString(valueCell);
                            if (s.length() > 0) {
                                pickLists.get(stringValue).add(s);
                            }
                        }
                    }
                }
            }
        });
    }

    String eol = System.getProperty("line.separator");

    StringBuilder sb = new StringBuilder();
    int i = 0;
    sb.append("public enum SHEET {");
    for (String s : sheets) {
        sb.append(enumSafeCharExchange(s));
        sb.append(", ");
        i++;
        if (i % 8 == 0) {
            i = 0;
            sb.append(eol);
        }
    }
    sb.setLength(sb.length() - (i == 0 ? 3 : 2));
    sb.append("};");
    System.out.println(sb);
    System.out.println();

    sb.setLength(0);
    i = 0;
    sb.append("public enum COLUMN {");
    for (String c : columns) {
        sb.append(enumSafeCharExchange(c));
        sb.append(", ");
        i++;
        if (i % 8 == 0) {
            i = 0;
            sb.append(eol);
        }
    }
    sb.setLength(sb.length() - (i == 0 ? 3 : 2));
    sb.append("};");
    System.out.println(sb);
    sb.setLength(0);
    i = 0;

    for (Entry<String, ArrayList<String>> x : pickLists.entrySet()) {
        sb.append("public enum PICKLIST_");
        sb.append(enumSafeCharExchange(x.getKey()));
        sb.append(" {");
        for (String s : x.getValue()) {
            sb.append(enumSafeCharExchange(s));
            sb.append("(\"");
            sb.append(s);
            sb.append("\")");
            sb.append(", ");
            i++;
            if (i % 2 == 0) {
                i = 0;
                sb.append(eol);
            }
        }
        sb.setLength(sb.length() - (i == 0 ? 3 : 2));
        sb.append(";" + eol);
        sb.append("\tprivate String value;" + eol + eol);
        sb.append("\tprivate PICKLIST_" + enumSafeCharExchange(x.getKey()) + " (String pickListValue)" + eol);
        sb.append("\t{" + eol);
        sb.append("\t\tvalue = pickListValue;" + eol);
        sb.append("\t}" + eol);

        sb.append("" + eol);
        sb.append("\t@Override" + eol);
        sb.append("\tpublic String toString()" + eol);
        sb.append("\t{" + eol);
        sb.append("\t\treturn value;" + eol);
        sb.append("\t}" + eol);

        sb.append("" + eol);
        sb.append("\tpublic static PICKLIST_" + enumSafeCharExchange(x.getKey()) + " find(String value)" + eol);
        sb.append("\t{" + eol);
        sb.append("\t\treturn PICKLIST_" + enumSafeCharExchange(x.getKey())
                + ".valueOf(enumSafeCharExchange(value));" + eol);
        sb.append("\t}" + eol);
        sb.append("};");

        System.out.println(sb);
        sb.setLength(0);
        i = 0;
        System.out.println();
    }
}

From source file:hjow.hgtable.util.XLSXUtil.java

License:Apache License

/**
 * <p>XLSX ? ?  ?? . ?  ?  ?? ?? , ? ? ?? ?  ?  ?? ?.</p>
 * /*from  ww w.ja v a2s  .c  om*/
 * @param file : XLSX ?
 * @return ?  ? 
 */
public static List<TableSet> toTableSets(File file) {
    List<TableSet> tableSets = new Vector<TableSet>();

    org.apache.poi.ss.usermodel.Workbook workbook = null;

    if (file == null)
        throw new NullPointerException(Manager.applyStringTable("Please select file !!"));
    if (!file.exists())
        throw new NullPointerException(Manager.applyStringTable("File") + " " + file.getAbsolutePath() + " "
                + Manager.applyStringTable("is not exist"));

    boolean isHead = true;
    int rowNum = 0;
    int cellNum = 0;

    int cellCount = 0;

    FileInputStream fileStream = null;
    try {
        if (file.getAbsolutePath().endsWith(".xlsx") || file.getAbsolutePath().endsWith(".XLSX")) {
            workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook(file);
        } else if (file.getAbsolutePath().endsWith(".xls") || file.getAbsolutePath().endsWith(".XLS")) {
            fileStream = new FileInputStream(file);
            workbook = new org.apache.poi.hssf.usermodel.HSSFWorkbook(fileStream);
        }

        org.apache.poi.ss.usermodel.FormulaEvaluator evals = workbook.getCreationHelper()
                .createFormulaEvaluator();

        org.apache.poi.ss.usermodel.Sheet sheet = null;

        for (int x = 0; x < workbook.getNumberOfSheets(); x++) {
            TableSet newTableSet = new DefaultTableSet();
            newTableSet.setColumns(new Vector<Column>());

            sheet = workbook.getSheetAt(x);
            newTableSet.setName(sheet.getSheetName());

            rowNum = 0;
            isHead = true;

            String targetData = null;

            for (org.apache.poi.ss.usermodel.Row row : sheet) {
                cellNum = 0;
                for (org.apache.poi.ss.usermodel.Cell cell : row) {
                    try {
                        if (cellNum >= cellCount) {
                            throw new IndexOutOfBoundsException(
                                    Manager.applyStringTable("There are some cells not have their heads") + ", "
                                            + Manager.applyStringTable("Head count") + " : " + cellCount + ", "
                                            + Manager.applyStringTable("Cell Number") + " : " + cellNum);
                        }

                        switch (cell.getCellType()) {
                        case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING:
                            if (isHead) {
                                newTableSet.getColumns().add(new Column(
                                        cell.getRichStringCellValue().getString(), Column.TYPE_STRING));
                            } else {
                                targetData = cell.getRichStringCellValue().getString();
                                newTableSet.getColumns().get(cellNum).setType(cell.getCellType());
                            }
                            break;
                        case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC:
                            if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                                if (isHead) {
                                    newTableSet.getColumns().add(new Column(
                                            String.valueOf(cell.getStringCellValue()), Column.TYPE_DATE));
                                } else {
                                    targetData = String.valueOf(cell.getDateCellValue());
                                    newTableSet.getColumns().get(cellNum).setType(cell.getCellType());
                                }
                            } else {
                                if (isHead) {
                                    newTableSet.getColumns().add(new Column(
                                            String.valueOf(cell.getStringCellValue()), Column.TYPE_NUMERIC));
                                } else {
                                    double values = cell.getNumericCellValue();
                                    double intPart = values - ((double) ((int) values));
                                    if (intPart == 0.0) {
                                        targetData = String.valueOf(((int) values));
                                        newTableSet.getColumns().get(cellNum).setType(Column.TYPE_INTEGER);
                                    } else {
                                        targetData = String.valueOf(values);
                                        newTableSet.getColumns().get(cellNum).setType(cell.getCellType());
                                    }
                                }
                            }
                            break;
                        case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN:
                            if (isHead) {
                                newTableSet.getColumns().add(new Column(
                                        String.valueOf(cell.getStringCellValue()), Column.TYPE_BOOLEAN));
                            } else {
                                targetData = String.valueOf(cell.getBooleanCellValue());
                                newTableSet.getColumns().get(cellNum).setType(cell.getCellType());
                            }
                            break;
                        case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_FORMULA:
                            if (isHead) {
                                newTableSet.getColumns().add(new Column(
                                        String.valueOf(cell.getStringCellValue()), Column.TYPE_NUMERIC));
                            } else {
                                if (evals.evaluateFormulaCell(cell) == 0) {
                                    targetData = String.valueOf(cell.getNumericCellValue());
                                    newTableSet.getColumns().get(cellNum).setType(Column.TYPE_NUMERIC);
                                } else if (evals.evaluateFormulaCell(cell) == 1) {
                                    targetData = String.valueOf(cell.getStringCellValue());
                                    newTableSet.getColumns().get(cellNum).setType(Column.TYPE_STRING);
                                } else if (evals.evaluateFormulaCell(cell) == 4) {
                                    targetData = String.valueOf(cell.getBooleanCellValue());
                                    newTableSet.getColumns().get(cellNum).setType(Column.TYPE_BOOLEAN);
                                } else {
                                    targetData = String.valueOf(cell.getCellFormula());
                                    newTableSet.getColumns().get(cellNum).setType(cell.getCellType());
                                }
                            }
                            break;
                        case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BLANK:
                            if (isHead) {
                                newTableSet.getColumns().add(new Column("", Column.TYPE_STRING));
                            } else {
                                targetData = "";
                                newTableSet.getColumns().get(cellNum).setType(Column.TYPE_BLANK);
                            }
                            break;
                        default:
                            if (isHead) {
                                newTableSet.getColumns().add(new Column("", Column.TYPE_STRING));
                            } else {
                                try {
                                    targetData = cell.getStringCellValue();
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                                newTableSet.getColumns().get(cellNum).setType(cell.getCellType());
                            }
                            break;
                        }

                        if (isHead) {
                            cellCount++;
                        } else {
                            while (rowNum > 0
                                    && newTableSet.getColumns().get(cellNum).getData().size() < rowNum) {
                                newTableSet.getColumns().get(cellNum).getData().add("");
                            }
                            if (targetData != null)
                                newTableSet.getColumns().get(cellNum).getData().add(targetData);
                            else {
                                newTableSet.getColumns().get(cellNum).getData().add("");
                            }
                        }
                    } catch (ArrayIndexOutOfBoundsException e1) {
                        StringBuffer err = new StringBuffer("");
                        for (StackTraceElement errEl : e1.getStackTrace()) {
                            err = err.append("\t " + errEl + "\n");
                        }

                        String cellObject = null;
                        try {
                            cellObject = cell.getStringCellValue();
                        } catch (Exception e2) {

                        }

                        throw new ArrayIndexOutOfBoundsException(
                                Manager.applyStringTable("Array index out of range") + " <- "
                                        + Manager.applyStringTable("Reading xlsx file") + " : " + file.getName()
                                        + ", " + sheet.getSheetName() + "\n" + Manager.applyStringTable("On")
                                        + " " + Manager.applyStringTable("Row") + " " + rowNum + ", "
                                        + Manager.applyStringTable("Cell") + " " + cellNum + ", "
                                        + Manager.applyStringTable("Value") + " : " + String.valueOf(cellObject)
                                        + "\n " + Manager.applyStringTable("<-\n") + err + "\n "
                                        + Manager.applyStringTable("Original Message") + "...\n"
                                        + e1.getMessage() + "\n" + Manager.applyStringTable("End"));
                    }

                    cellNum++;
                }

                isHead = false;
                rowNum++;
            }

            fillTableSet(newTableSet);
            newTableSet.removeEmptyColumn(true);

            tableSets.add(newTableSet);
        }

        return tableSets;
    } catch (Throwable e) {
        if (Main.MODE >= DebuggingUtil.DEBUG)
            e.printStackTrace();
        Main.logError(e,
                Manager.applyStringTable("On reading xlsx") + " : " + file + "\n"
                        + Manager.applyStringTable("At rownum") + " " + rowNum + ", "
                        + Manager.applyStringTable("cellnum") + " " + cellNum);

        return null;
    } finally {
        try {
            workbook.close();
        } catch (Throwable e) {

        }
        try {
            if (fileStream != null)
                fileStream.close();
        } catch (Throwable e) {

        }
    }
}

From source file:hu.webhejj.commons.io.table.excel.ExcelUtils.java

License:Apache License

public static void ensureSheet(Workbook workbook, int index) {
    for (int i = workbook.getNumberOfSheets(); i <= index; i++) {
        workbook.createSheet();/*  w w  w  .  java 2 s  .  c  o m*/
    }
}

From source file:info.informationsea.java.excel2csv.Converter.java

License:Open Source License

private void doConvertAllSheets(List<File> inputFiles, File outputFile) throws Exception {
    Workbook workbook;/*from   ww  w. j  a  va2 s  .c o m*/

    if (outputFile.isFile() && outputFile.length() > 512) {
        switch (Utilities.suggestFileTypeFromName(outputFile.getName())) {
        case FILETYPE_XLS:
        case FILETYPE_XLSX:
            workbook = WorkbookFactory.create(outputFile);
            break;
        default:
            throw new IllegalArgumentException("Output file format should be Excel format");
        }
    } else {
        switch (Utilities.suggestFileTypeFromName(outputFile.getName())) {
        case FILETYPE_XLS:
            workbook = new HSSFWorkbook();
            break;
        case FILETYPE_XLSX:
            if (largeExcelMode)
                workbook = new SXSSFWorkbook();
            else
                workbook = new XSSFWorkbook();
            break;
        default:
            throw new IllegalArgumentException("Output file format should be Excel format");
        }
    }

    if (largeExcelMode && !(workbook instanceof SXSSFWorkbook)) {
        log.warn("Streaming output mode is disabled");
    }
    //log.info("workbook: {}", workbook.getClass());

    for (File oneInput : inputFiles) {
        switch (Utilities.suggestFileTypeFromName(oneInput.getName())) {
        case FILETYPE_XLSX:
        case FILETYPE_XLS: {
            Workbook inputWorkbook = WorkbookFactory.create(oneInput);
            int sheetNum = inputWorkbook.getNumberOfSheets();
            for (int i = 0; i < sheetNum; i++) {
                try (TableReader reader = new ExcelSheetReader(inputWorkbook.getSheetAt(i))) {
                    ExcelSheetWriter sheetWriter = new ExcelSheetWriter(
                            Utilities.createUniqueNameSheetForWorkbook(workbook, inputWorkbook.getSheetName(i),
                                    overwriteSheet));
                    sheetWriter.setPrettyTable(prettyTable);
                    try (TableWriter tableWriter = new FilteredWriter(sheetWriter, convertCellTypes,
                            fistCount)) {
                        Utilities.copyTable(reader, tableWriter, useHeader);
                    }
                }
            }
            break;
        }
        default: {
            try (TableReader reader = Utilities.openReader(oneInput, inputSheetIndex, inputSheetName)) {
                ExcelSheetWriter sheetWriter = new ExcelSheetWriter(Utilities
                        .createUniqueNameSheetForWorkbook(workbook, oneInput.getName(), overwriteSheet));
                sheetWriter.setPrettyTable(prettyTable);
                try (TableWriter tableWriter = new FilteredWriter(sheetWriter, convertCellTypes, fistCount)) {
                    Utilities.copyTable(reader, tableWriter, useHeader);
                }
            }
            break;
        }
        }
    }

    workbook.write(new FileOutputStream(outputFile));
}

From source file:info.informationsea.java.excel2csv.ConverterTest.java

License:Open Source License

@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());/*ww  w.  j a va  2 s .com*/

    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());
        }
    }
}

From source file:info.informationsea.java.excel2csv.ConverterTest.java

License:Open Source License

@Test
public void testDoConvert5() throws Exception {
    Path temporaryOutput = Files.createTempFile("excel2csv", ".xlsx");
    Converter.builder().copyAllSheets(false).inputSheetName("DNase").outputSheetName("DNase").build().doConvert(
            Collections.singletonList(new File(temporaryDirectory.toFile(), "multisheet.xls")),
            temporaryOutput.toFile());//  w w  w .  j  a va  2  s.  c  om

    Workbook workbook = WorkbookFactory.create(temporaryOutput.toFile());
    Assert.assertEquals(1, workbook.getNumberOfSheets());
    for (String one : new String[] { "DNase" }) {
        try (TableReader reader = new ExcelSheetReader(workbook.getSheet(one))) {
            Excel2CSVTest.assertObjects(reference.get(one), reader.readAll());
        }
    }
}

From source file:info.informationsea.java.excel2csv.ConverterTest.java

License:Open Source License

@Test
public void testDoConvert6() throws Exception {
    Path temporaryOutput = Files.createTempFile("excel2csv", ".xlsx");
    Converter.builder().copyAllSheets(false).inputSheetIndex(2).outputSheetName("DNase").build().doConvert(
            Collections.singletonList(new File(temporaryDirectory.toFile(), "multisheet.xls")),
            temporaryOutput.toFile());/*w  ww  .j av a2s.  co  m*/

    Workbook workbook = WorkbookFactory.create(temporaryOutput.toFile());
    Assert.assertEquals(1, workbook.getNumberOfSheets());
    for (String one : new String[] { "DNase" }) {
        try (TableReader reader = new ExcelSheetReader(workbook.getSheet(one))) {
            Excel2CSVTest.assertObjects(reference.get(one), reader.readAll());
        }
    }
}

From source file:info.informationsea.java.excel2csv.Excel2CSVTest.java

License:Open Source License

@Test
public void testMultiSheet() throws Exception {
    Path outputFile = Files.createTempFile("outputTest", ".xlsx");
    new Excel2CSV().run(new String[] { sampleInput[0].toString(), outputFile.toString() });
    new Excel2CSV().run(new String[] { sampleInput[1].toString(), outputFile.toString() });
    new Excel2CSV().run(new String[] { sampleInput[0].toString(), outputFile.toString() });

    try (FileInputStream inputStream = new FileInputStream(outputFile.toFile())) {
        Workbook workbook = new XSSFWorkbook(inputStream);
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            log.info("sheet {}", workbook.getSheetName(i));
        }//w  w  w . j a  v a  2s .c o m
    }

    for (int i = 0; i < 3; i++) {
        try (TableReader tableReader = Utilities.openReader(outputFile.toFile(), i, null)) {
            assertObjects(expectedData, tableReader.readAll());
        }
    }

    try (TableReader tableReader = Utilities.openReader(outputFile.toFile(), 10,
            sampleInput[0].getFileName().toString())) {
        assertObjects(expectedData, tableReader.readAll());
    }

    try (TableReader tableReader = Utilities.openReader(outputFile.toFile(), 10,
            sampleInput[1].getFileName().toString())) {
        assertObjects(expectedData, tableReader.readAll());
    }

    try (TableReader tableReader = Utilities.openReader(outputFile.toFile(), 10,
            sampleInput[0].getFileName().toString() + "-1")) {
        assertObjects(expectedData, tableReader.readAll());
    }
}