Example usage for org.apache.poi.xssf.usermodel XSSFWorkbook XSSFWorkbook

List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook XSSFWorkbook

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFWorkbook XSSFWorkbook.

Prototype

public XSSFWorkbook(PackagePart part) throws IOException 

Source Link

Document

Constructs a XSSFWorkbook object using Package Part.

Usage

From source file:com.gsecs.GSECSFrame.java

private void ImportRoomMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ImportRoomMenuItemActionPerformed
    // TODO add your handling code here:
    JFileChooser jf = new JFileChooser();
    jf.setDialogTitle("Please select a excel File to import");
    int result = jf.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) {
        String filePath = jf.getSelectedFile().getAbsolutePath();

        try {//from w  w  w  . ja  v a 2 s  .  co m
            FileInputStream fis = new FileInputStream(filePath);
            Workbook workbook = new XSSFWorkbook(fis);
            Sheet firstSheet = workbook.getSheetAt(0);
            Iterator<Row> iterator = firstSheet.iterator();
            List<RoomBean> roomBeansList = new ArrayList<RoomBean>();

            while (iterator.hasNext()) {
                Row nextRow = iterator.next();
                if (nextRow.getRowNum() != 0) {
                    Iterator<Cell> cellIterator = nextRow.cellIterator();
                    RoomBean roomBean = new RoomBean();

                    while (cellIterator.hasNext()) {
                        Cell nextCell = cellIterator.next();
                        int columnIndex = nextCell.getColumnIndex();

                        switch (columnIndex) {
                        case 0:
                            roomBean.setRoomNumber(getCellValue(nextCell).toString());
                            break;
                        case 1:
                            roomBean.setCourseCode((String) getCellValue(nextCell));
                            break;
                        case 2:
                            roomBean.setCapacity((String) getCellValue(nextCell));
                            break;

                        }

                    }
                    roomBeansList.add(roomBean);
                }

            }
            workbook.close();
            fis.close();

            mainPanel.removeAll();
            mainPanel.repaint();
            RoomModel model = new RoomModel();
            RoomJInternalFrame roomFrame = new RoomJInternalFrame();
            roomFrame.getRoomMsgLabel().setText("");
            roomFrame.getAddRoomButton().setVisible(true);
            roomFrame.getUpdateRoomButton().setVisible(false);
            roomFrame.getDeleteRoomButton().setVisible(false);
            //userFrame.getSchoolDataTable().setModel(DbUtils.resultSetToTableModel( new GradSchoolModel().getAllSchools()));
            for (RoomBean roomBean : roomBeansList) {
                try {
                    model.addRoom(roomBean);
                } catch (Exception exp) {
                    System.out.println("Exception Raised....." + exp.getMessage());
                }
            }
            roomFrame.loadDataIntoJTable();
            mainPanel.add(roomFrame);
            roomFrame.setVisible(true);
        } catch (Exception exp) {
            JOptionPane.showMessageDialog(null, exp.getMessage());
        }

    }
}

From source file:com.gtja.qh.TransferCtrl.TransferCtrl.java

private boolean transferToTxt(String inputFilePath, String outFileDir) {
    File inputFile = new File(inputFilePath);
    String inputFileName = inputFile.getName();
    String extension = inputFileName.lastIndexOf(".") == -1 ? ""
            : inputFileName.substring(inputFileName.lastIndexOf(".") + 1);
    StringBuffer input = null;//w  ww. jav a  2s .c o  m
    if ("xls".equals(extension)) {
        //JXL?excel 2003??xlsx?
        try {
            //?excel
            InputStream is = new FileInputStream(inputFilePath);
            jxl.Workbook rwb = jxl.Workbook.getWorkbook(is);
            jxl.Sheet rs = rwb.getSheet(0);
            int rsRows = rs.getRows();
            input = new StringBuffer();
            for (int i = 1; i < rsRows; i++) {
                if (rs.getCell(5, i).getContents().equals("")) {
                    String line = "A999@" + rs.getCell(4, i).getContents() + "@"
                            + rs.getCell(6, i).getContents() + "\r\n";
                    line = line.replaceAll(",", "");
                    input.append(line);
                } else {
                    continue;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    } else if ("xlsx".equals(extension)) {
        //POI ?excel 2007,??excel 2003
        try {
            InputStream fs = new FileInputStream(inputFilePath);
            XSSFWorkbook wb;
            wb = new XSSFWorkbook(fs);
            XSSFSheet sheet = wb.getSheetAt(0);
            int rows = sheet.getPhysicalNumberOfRows();
            input = new StringBuffer();
            for (int i = 1; i < rows; i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                if (row.getCell(5).getStringCellValue().equals("")) {
                    if (row.getCell(4) == null) {
                        row.createCell(4);
                        row.getCell(4).setCellValue("");
                    }
                    if (row.getCell(6) == null) {
                        row.createCell(6);
                        row.getCell(6).setCellValue("");
                    }

                    String tradeCode = row.getCell(4).getStringCellValue();
                    Double amount = null;
                    String amt = null;
                    if (row.getCell(6).getCellType() == CELL_TYPE_NUMERIC) {
                        amount = row.getCell(6).getNumericCellValue();
                        amt = new DecimalFormat("0.00").format(amount);
                    } else {
                        if (row.getCell(6).getStringCellValue().length() == 0) {
                            amount = null;
                            amt = "";
                        } else {
                            amount = new DecimalFormat("0.00").parse(row.getCell(6).getStringCellValue())
                                    .doubleValue(); //String?Double
                            amt = amount.toString();
                        }
                    }
                    String line = "A999@" + tradeCode + "@" + amt + "\r\n";
                    line = line.replaceAll(",", "");
                    input.append(line);
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    try {
        //
        String fileName = "0004_00000001_" + frame.getDate().getText() + "_DailyFundChg";
        String outFile = outFileDir + "\\" + fileName + ".txt";
        File file = new File(outFile);
        if (!file.exists()) {
            file.createNewFile();
        }
        //
        OutputStream os = new FileOutputStream(file);
        os.write(input.toString().getBytes());
        os.flush();
        os.close();
        return true;

    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "???",
                "?", JOptionPane.ERROR_MESSAGE);
        return false;
    }

}

From source file:com.gtja.qh.TransferCtrl.TransferCtrl.java

private boolean transferToDbf(String inputFilePath, String outFileDir) throws DBFException {

    //DBF,?//from w w  w  .  j av  a 2 s. c  o m
    DBFField[] fields = new DBFField[6];

    fields[0] = new DBFField();
    fields[0].setName("ACCOUNTID");
    fields[0].setDataType(DBFField.FIELD_TYPE_C);
    fields[0].setFieldLength(6);

    fields[1] = new DBFField();
    fields[1].setName("PARTID");
    fields[1].setDataType(DBFField.FIELD_TYPE_C);
    fields[1].setFieldLength(4);

    fields[2] = new DBFField();
    fields[2].setName("CLIENTID");
    fields[2].setDataType(DBFField.FIELD_TYPE_C);
    fields[2].setFieldLength(8);

    fields[3] = new DBFField();
    fields[3].setName("AMOUNT");
    fields[3].setDataType(DBFField.FIELD_TYPE_N);
    fields[3].setFieldLength(23);
    fields[3].setDecimalCount(2);

    fields[4] = new DBFField();
    fields[4].setName("MONEYTYPE");
    fields[4].setDataType(DBFField.FIELD_TYPE_C);
    fields[4].setFieldLength(4);

    fields[5] = new DBFField();
    fields[5].setName("TYPEMEMO");
    fields[5].setDataType(DBFField.FIELD_TYPE_C);
    fields[5].setFieldLength(40);
    DBFWriter writer = new DBFWriter();
    try {
        writer.setFields(fields);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    //excel??
    File inputFile = new File(inputFilePath);
    String inputFileName = inputFile.getName();
    String extension = inputFileName.lastIndexOf(".") == -1 ? ""
            : inputFileName.substring(inputFileName.lastIndexOf(".") + 1);
    if ("xls".equals(extension)) {
        //JXL?excel 2003??xlsx?
        try {
            //?excel
            InputStream is = new FileInputStream(inputFilePath);
            jxl.Workbook rwb = jxl.Workbook.getWorkbook(is);
            jxl.Sheet rs = rwb.getSheet(0);
            int rsRows = rs.getRows();
            for (int i = 1; i < rsRows; i++) {
                if (rs.getCell(5, i).getContents().equals("")) {
                    Object[] rowData = new Object[6];
                    rowData[0] = "000101";
                    rowData[1] = "0001";
                    rowData[4] = "A999";
                    String tradeCode = rs.getCell(4, i).getContents();
                    Double amount = null;
                    if (rs.getCell(6, i).getType() == CellType.NUMBER) {
                        NumberCell numberCell = (NumberCell) rs.getCell(6, i);
                        amount = numberCell.getValue();
                    } else {
                        if (rs.getCell(6, i).getContents().length() == 0) {
                            amount = null;
                        } else {
                            amount = new DecimalFormat("0.00").parse(rs.getCell(6, i).getContents())
                                    .doubleValue(); //String?Double 
                        }

                    }
                    String typeMemo = rs.getCell(7, i).getContents();
                    rowData[2] = tradeCode;
                    rowData[3] = amount;
                    rowData[5] = typeMemo;
                    writer.addRecord(rowData);
                } else {
                    continue;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    } else if ("xlsx".equals(extension)) {
        //POI ?excel 2007,??excel 2003
        try {
            InputStream fs = new FileInputStream(inputFilePath);
            XSSFWorkbook wb;
            wb = new XSSFWorkbook(fs);
            //wb = new XSSFWorkbook(inputFilePath);
            XSSFSheet sheet = wb.getSheetAt(0);
            int rows = sheet.getPhysicalNumberOfRows();
            for (int i = 1; i < rows; i++) {

                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                if (row.getCell(5).getStringCellValue().equals("")) {
                    Object[] rowData = new Object[6];
                    rowData[0] = "000101";
                    rowData[1] = "0001";
                    rowData[4] = "A999";
                    if (row.getCell(4) == null) {
                        row.createCell(4);
                        row.getCell(4).setCellValue("");
                    }
                    if (row.getCell(6) == null) {
                        row.createCell(6);
                        row.getCell(6).setCellValue("");
                    }
                    if (row.getCell(7) == null) {
                        row.createCell(7);
                        row.getCell(7).setCellValue("");
                    }
                    String tradeCode = row.getCell(4).getStringCellValue();
                    Double amount = null;
                    if (row.getCell(6).getCellType() == CELL_TYPE_NUMERIC) {
                        amount = row.getCell(6).getNumericCellValue();
                    } else {
                        row.getCell(6).setCellType(CELL_TYPE_STRING);
                        if (row.getCell(6).getStringCellValue().length() == 0) {
                            amount = null;
                        } else {
                            amount = new DecimalFormat("0.00").parse(row.getCell(6).getStringCellValue())
                                    .doubleValue();
                        }
                    }
                    String typeMemo = row.getCell(7).getStringCellValue();
                    rowData[2] = tradeCode;
                    rowData[3] = amount;
                    rowData[5] = typeMemo;
                    writer.addRecord(rowData);
                } else {
                    continue;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    try {
        //
        String fileName = "0001_SG01_" + frame.getDate().getText() + "_1_ClientCapitalDetail";
        String outFile = outFileDir + "\\" + fileName + ".dbf";
        File file = new File(outFile);
        if (!file.exists()) {
            file.createNewFile();
        }
        OutputStream os = new FileOutputStream(file);
        writer.write(os); //? 
        os.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "???",
                "?", JOptionPane.ERROR_MESSAGE);
        return false;
    }
}

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 ww w . ja va2 s .  c  o  m
        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.hauldata.dbpa.file.book.XlsxSourceBook.java

License:Apache License

@Override
public void open() throws IOException {

    try {//from   www .ja  va2s  .  co  m
        pkg = OPCPackage.open(new java.io.File(getName()));
        book = new XSSFWorkbook(pkg);
    } catch (InvalidFormatException ex) {
        throw new RuntimeException(ex.getMessage());
    }
}

From source file:com.heimaide.server.common.utils.excel.ExportExcel.java

License:Open Source License

private void exportFile(List<String> list, String rootPath, HttpServletResponse response,
        List<List<Object>> bodyList) throws FileNotFoundException, IOException {
    String importFileName = rootPath + "WEB-INF" + File.separator + "xlsx" + File.separator + "order.xlsx";
    String tmpDir = rootPath + "tmpDir" + File.separator;
    XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(importFileName));
    this.styles = createStyles(wb);
    //?excel?  //from w w  w.j  a  v  a2s .  c  om
    //??sheet  
    XSSFSheet sheet = wb.getSheetAt(0);
    XSSFCell cell1 = sheet.getRow(1).getCell(0);
    String cell1str = cell1.getStringCellValue();
    //????
    cell1str = cell1str.replace("X", list.get(0));
    cell1.setCellValue(cell1str);
    XSSFCell cell2 = sheet.getRow(2).getCell(0);
    String cell2str = cell2.getStringCellValue();
    //??
    cell2str = cell2str.replace("X", list.get(1));
    //?
    cell2str = cell2str.replace("Y", list.get(2));
    //???
    cell2str = cell2str.replace("Z", list.get(3));
    cell2.setCellValue(cell2str);
    XSSFCell cell3 = sheet.getRow(3).getCell(12);
    String cell3str = cell3.getStringCellValue();
    cell3str = cell3str.replace("XX", list.get(4));
    cell3.setCellValue(cell3str);

    XSSFCell cell4 = sheet.getRow(sheet.getLastRowNum() - 1).getCell(0);
    String cell4str = cell4.getStringCellValue();
    cell4str = cell4str.replace("X", list.get(5));
    cell4.setCellValue(cell4str);

    XSSFCell cell5 = sheet.getRow(sheet.getLastRowNum() - 4).getCell(12);
    XSSFCell cell6 = sheet.getRow(sheet.getLastRowNum() - 4).getCell(13);
    String str1 = String.valueOf(list.get(6));
    String str2 = String.valueOf(list.get(7));
    str1 = str1.substring(0, str1.indexOf("."));
    str2 = str2.substring(0, str2.indexOf("."));
    cell5.setCellValue(str1);

    cell6.setCellValue(str2);

    XSSFCell cell7 = sheet.getRow(sheet.getLastRowNum() - 3).getCell(12);
    XSSFCell cell8 = sheet.getRow(sheet.getLastRowNum() - 3).getCell(13);
    cell7.setCellValue(Double.parseDouble(list.get(6)) / 10);
    cell8.setCellValue(Double.parseDouble(list.get(7)) / 10);
    //                 int columnNum =sheet.getRow(3).getLastCellNum();
    //                 int column =0;
    //                 for(int i=0;i<columnNum;i++)
    //                 {
    //                    System.out.println("==="+sheet.getRow(3).getCell(i).getStringCellValue());
    //                    column =i;
    //                 }

    int num = 5;
    for (int i = 0; i < bodyList.size(); i++) {
        List<Object> strList = bodyList.get(i);
        sheet.shiftRows(num, bodyList.size() + num, 1, true, false);
        sheet.createRow(num);

        for (int j = 0; j < strList.size(); j++) {
            Row row = sheet.getRow(num);
            addCell(row, j, strList.get(j));
            //                       Cell cell = row.createCell(j);
            //                       cell.setCellValue(strList.get(j));
        }
        num++;
    }

    //??  
    String tmpName = tmpDir + "tmp_hmd.xlsx";
    File dirFile = new File(tmpDir);
    if (!dirFile.exists()) {
        dirFile.mkdir();
    }
    File tmpFile = new File(tmpName);
    FileOutputStream fos = new FileOutputStream(tmpFile);
    wb.write(fos);

    XSSFWorkbook wb1 = new XSSFWorkbook(new FileInputStream(tmpName));
    response.reset();
    response.setContentType("application/octet-stream; charset=utf-8");
    response.setHeader("Content-Disposition",
            "attachment; filename=" + Encodes.urlEncode("?" + list.get(0) + "?.xlsx"));
    wb1.write(response.getOutputStream());

    tmpFile.delete();
}

From source file:com.helger.poi.excel.ExcelReadUtils.java

License:Apache License

/**
 * Try to read an Excel {@link Workbook} from the passed
 * {@link IInputStreamProvider}. First XLS is tried, than XLSX, as XLS files
 * can be identified more easily./* w ww .  j a v a 2 s.co  m*/
 * 
 * @param aIIS
 *        The input stream provider to read from.
 * @return <code>null</code> if the content of the InputStream could not be
 *         interpreted as Excel file
 */
@Nullable
public static Workbook readWorkbookFromInputStream(@Nonnull final IInputStreamProvider aIIS) {
    InputStream aIS = null;
    try {
        // Try to read as XLS
        aIS = aIIS.getInputStream();
        if (aIS == null) {
            // Failed to open input stream -> no need to continue
            return null;
        }
        return new HSSFWorkbook(aIS);
    } catch (final IOException ex) {
        s_aLogger.error("Error trying to read XLS file from " + aIIS, ex);
    } catch (final OfficeXmlFileException ex) {
        // No XLS -> try XSLS
        StreamUtils.close(aIS);
        try {
            // Re-retrieve the input stream, to ensure we read from the beginning!
            aIS = aIIS.getInputStream();
            return new XSSFWorkbook(aIS);
        } catch (final IOException ex2) {
            s_aLogger.error("Error trying to read XLSX file from " + aIIS, ex);
        } catch (final POIXMLException ex2) {
            // No XLSX either -> no valid Excel file
        }
    } finally {
        // Ensure the InputStream is closed. The data structures are in memory!
        StreamUtils.close(aIS);
    }
    return null;
}

From source file:com.hp.idc.resm.util.ExcelUtil.java

License:Open Source License

/**
 * ,/*from w  w w . j  a  va  2 s .  c  o m*/
 * 
 * @param fileName
 *            excel, getModelExcel
 * @return 
 * @throws FileNotFoundException 
 */
public Map<String, String> readModelExcel(File file, String modelId) {
    if (modelId == null)
        return null;
    Map<String, String> m = new HashMap<String, String>();
    try {
        InputStream in = new FileInputStream(file);
        Workbook wb;
        try {
            wb = new HSSFWorkbook(in);
        } catch (IllegalArgumentException e) {
            wb = new XSSFWorkbook(in);
        }
        Sheet sheet = wb.getSheetAt(0);
        int total = sheet.getLastRowNum();
        Row row0 = sheet.getRow(0);
        String[] head = new String[row0.getLastCellNum()];
        for (int j = 0; j < row0.getLastCellNum(); j++) {
            String[] str = row0.getCell(j).getStringCellValue().split("/");
            if (str.length == 2) {
                head[j] = str[1];
            } else {
                head[j] = "";
            }
            System.out.println(head[j]);
        }
        Row row = null;
        Cell cell = null;
        for (int i = 1; i < total; i++) {
            m.clear();
            row = sheet.getRow(i);
            for (int j = 0; j < row.getLastCellNum(); j++) {
                cell = row.getCell(j);
                m.put(head[j], cell.getStringCellValue());
                System.out.println(head[j] + "--" + cell.getStringCellValue());
            }
            // ServiceManager.getResourceUpdateService().addResource(modelId,
            // m, 1);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        file.delete();
    }
    return m;
}

From source file:com.huawei.gsm.controller.AdminController.java

private void parseExcelFile(File file) throws IOException, InvalidFormatException {

    XSSFWorkbook workbook = new XSSFWorkbook(file);
    XSSFSheet sheet = workbook.getSheetAt(0);

    Iterator<Row> rowIterator = sheet.iterator();

    Map<String, Site> sites = new HashMap<>();
    Set<Cell> cells = new HashSet<>();

    if (rowIterator.hasNext()) {
        rowIterator.next();//from   www .  j  ava2  s.c o  m
    }

    int i = 0;

    while (rowIterator.hasNext()) {

        Row row = rowIterator.next();
        String siteId;
        String cellIndex;
        String cellId;

        try {
            row.getCell(1).getStringCellValue();
        } catch (NullPointerException ex) {
            break;
        }

        if (row.getCell(0).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
            double sId = row.getCell(0).getNumericCellValue();
            siteId = String.valueOf(sId).replaceAll("\\.?0*$", "");
        } else {
            siteId = row.getCell(0).getStringCellValue();
        }

        if (row.getCell(6).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
            double cId = row.getCell(6).getNumericCellValue();
            cellIndex = String.valueOf(cId).replaceAll("\\.?0*$", "");
        } else {
            cellIndex = row.getCell(6).getStringCellValue();
        }

        if (row.getCell(8).getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
            double ceId = row.getCell(8).getNumericCellValue();
            cellId = String.valueOf(ceId).replaceAll("\\.?0*$", "");
        } else {
            cellId = row.getCell(8).getStringCellValue();
        }

        Site site = new Site();
        site.setAddress(row.getCell(2).getStringCellValue());
        site.setGroup((row.getCell(5).getStringCellValue().toLowerCase().equalsIgnoreCase("GOLDEN_SITE")
                ? SiteGroup.GOLDEN_SITE
                : SiteGroup.EVENT_SITE));
        site.setSiteId(siteId);
        site.setSiteName(row.getCell(1).getStringCellValue());
        site.setLatitude(row.getCell(4).getNumericCellValue());
        site.setLongitude(row.getCell(3).getNumericCellValue());
        site.setCells(new ArrayList<>());

        sites.put(siteId, site);

        Cell cell = new Cell();
        cell.setCellId(cellId);
        cell.setCellIndex(cellIndex);
        cell.setCellName(row.getCell(7).getStringCellValue());
        cell.setFrequency(row.getCell(9).getStringCellValue());
        cell.setSite(site);

        cells.add(cell);

        i++;

    }

    Iterator<Site> iter = sites.values().iterator();
    while (iter.hasNext()) {
        Site site = iter.next();

        cells.stream().filter((Cell s) -> {
            return s.getSite().getSiteId().equalsIgnoreCase(site.getSiteId());
        }).forEach(s -> {
            site.getCells().add(s);
        });

    }

    List<Site> sitesX = new ArrayList<>(sites.values());

    siteService.saveSiteBatch(sitesX);

}

From source file:com.hust.zsuper.DealWithPatent.Utils.java

License:Open Source License

public static Workbook createWorkbook(File file) throws IOException {
    if (file.getName().endsWith(".xls")) {
        return new HSSFWorkbook(new FileInputStream(file));
    } else if (file.getName().endsWith(".xlsx")) {
        return new XSSFWorkbook(file.getAbsolutePath());
    }/*ww w  .  java  2 s  . c om*/
    return null;
}