Example usage for org.apache.poi.ss.usermodel WorkbookFactory create

List of usage examples for org.apache.poi.ss.usermodel WorkbookFactory create

Introduction

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

Prototype

public static Workbook create(File file) throws IOException, EncryptedDocumentException 

Source Link

Document

Creates the appropriate HSSFWorkbook / XSSFWorkbook from the given File, which must exist and be readable.

Usage

From source file:jp.qpg.ExcelTo.java

License:Apache License

/**
 * command/*from ww  w  . j  av  a2s.c  o m*/
 * 
 * @param args [-p password] [-m true|false(draw margin line if true)] Excel files(.xls, .xlsx, .xlsm)
 */
public static void main(String[] args) {
    Objects.requireNonNull(args);
    int count = 0;
    boolean[] drawMarginLine = { false };
    for (int i = 0; i < args.length; i++) {
        switch (args[i]) {
        case "-m":/* set draw margin line */
            i++;
            drawMarginLine[0] = Boolean.parseBoolean(args[i]);
            break;
        case "-p":/* set password */
            i++;
            Biff8EncryptionKey.setCurrentUserPassword(args[i]);
            break;
        default:
            String path = Tool.trim(args[i], "\"", "\"");
            String toPath = Tool.changeExtension(path, ".pdf");
            String toTextPath = Tool.changeExtension(path, ".txt");
            try (InputStream in = Files.newInputStream(Paths.get(path));
                    Workbook book = WorkbookFactory.create(in);
                    OutputStream out = Files.newOutputStream(Paths.get(toPath));
                    OutputStream outText = Files.newOutputStream(Paths.get(toTextPath))) {
                logger.info("processing: " + path);
                pdf(book, out, printer -> {
                    printer.setPageSize(PDRectangle.A4, false);
                    printer.setFontSize(10.5f);
                    printer.setMargin(15);
                    printer.setLineSpace(5);
                    printer.setDrawMarginLine(drawMarginLine[0]);
                });
                text(book, outText);
                logger.info("converted: " + toPath + ", " + toTextPath);
                count++;
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            break;
        }
    }
    logger.info("processed " + count + " files.");
}

From source file:Logica.L_Exel.java

public String Importar(File archivo, JTable tablaD) {
    String respuesta = "Revisr";
    DefaultTableModel model = new DefaultTableModel();
    tablaD.setModel(model);/*from w  w w.  j a v  a  2 s .c  o m*/
    try {
        wb = WorkbookFactory.create(new FileInputStream(archivo));
        Sheet Hoja = wb.getSheetAt(0);
        Iterator filaIterator = Hoja.rowIterator();
        int indiceFila = -1;
        while (filaIterator.hasNext()) {
            indiceFila++;
            Row fila = (Row) filaIterator.next();
            Iterator columnaIterator = fila.cellIterator();
            Object[] ListaColumna = new Object[7];
            int indicecolumna = -1;
            while (columnaIterator.hasNext()) {
                indicecolumna++;
                Cell celda = (Cell) columnaIterator.next();
                if (indiceFila == 0) {
                    model.addColumn(celda.getStringCellValue());
                } else {
                    if (celda != null) {
                        switch (celda.getCellType()) {
                        case Cell.CELL_TYPE_NUMERIC:
                            ListaColumna[indicecolumna] = (int) Math.round(celda.getNumericCellValue());
                            break;
                        case Cell.CELL_TYPE_STRING:
                            ListaColumna[indicecolumna] = celda.getStringCellValue();
                            break;
                        case Cell.CELL_TYPE_BOOLEAN:
                            ListaColumna[indicecolumna] = celda.getBooleanCellValue();
                            break;
                        default:
                            ListaColumna[indicecolumna] = celda.getDateCellValue();
                            break;
                        }
                    }
                }
            }
            if (indiceFila != 0)
                model.addRow(ListaColumna);
        }
        respuesta = "Funciona";
    } catch (Exception e) {
    }
    return respuesta;
}

From source file:lp.XLSXhandler.java

public void create_xlsx_file(String absolute, String model, Object[] obj, double[][] results) {

    /*/*from  w  ww.  j  av  a2 s  .c o m*/
     obj[0] = data; --
     obj[1] = rows;
     obj[2] = columns;
     obj[3] = variables; --
     obj[4] = dmu Names; --
     */
    double[][] data = (double[][]) obj[0];

    // Rows number in file
    int rows_number = (Integer) obj[1];

    // Columns in file (1-based)
    int col_number = (Integer) obj[2];
    //int res = results.length;
    int results_number = results[0].length;
    int total_col = col_number + results_number;//9

    String[] dmuNames = (String[]) obj[4];

    String[] var = (String[]) obj[3];
    String[] variables = new String[0];

    /*
     Get the selected model/s and create the matrix "variables" 
     for each model respectively.
     */
    if (model.equals("multiplicative") || model.equals("composition")) {

        variables = new String[total_col];
        System.arraycopy(var, 0, variables, 0, var.length);

        variables[col_number] = "e1";
        variables[col_number + 1] = "e2";
        variables[col_number + 2] = "Overall Efficiency";
    }
    if (model.equals("additive")) {

        variables = new String[total_col];
        System.arraycopy(var, 0, variables, 0, var.length);

        variables[col_number] = "Weight 1";
        variables[col_number + 1] = "Weight 2";
        variables[col_number + 2] = "Overall Efficiency";
        variables[col_number + 3] = "Theta 1";
        variables[col_number + 4] = "Theta 2";

    }

    try {
        Workbook wb = new XSSFWorkbook();
        FileOutputStream fileOut = new FileOutputStream(absolute + "\\" + model + ".xlsx");
        wb.write(fileOut);
        fileOut.close();

        InputStream inp = new FileInputStream(absolute + "\\" + model + ".xlsx");
        wb = WorkbookFactory.create(inp);
        Sheet sheet = wb.createSheet("new");
        sheet = wb.getSheetAt(0);

        //int rows_number = results.length;
        //int col_number = results[0].length;
        Row row = sheet.createRow(0);

        row = sheet.getRow(0);
        if (row == null) {
            row = sheet.createRow(0);
        }

        Cell cell = row.getCell(0);
        if (cell == null) {

            //the first ROW: the names and variable names for each column
            for (int l = 0; l < variables.length; l++) {
                cell = row.createCell(l, cell.CELL_TYPE_STRING);
                cell.setCellValue(variables[l]);
            }

            for (int i = 0; i < rows_number; i++) {

                row = sheet.createRow(i + 1);
                int helper = 0;
                //the rest file...
                for (int k = 0; k < total_col + 1; k++) {

                    if (k == 0) {
                        //the first column (dmu names)
                        cell = row.createCell(k, cell.CELL_TYPE_STRING);
                        cell.setCellValue(dmuNames[i]);

                    }
                    if (k > 0 && k < col_number) {
                        //the rest of the columns with data
                        cell = row.createCell(k, cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(data[i][k - 1]);

                    }

                    if (k >= col_number && helper < results_number) {
                        //the columns with efficiency results
                        cell = row.createCell(k, cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(results[i][helper]);
                        helper++;
                    }

                }

            }
        }

        // Write the output to a file
        FileOutputStream fOut = new FileOutputStream(absolute + "\\" + model + ".xlsx");
        wb.write(fOut);
        fOut.close();
        inp.close();

    } catch (FileNotFoundException e) {
        System.out.println("--EXCEPTION: " + e.getMessage());
    } catch (IOException e) {
        System.out.println("--EXCEPTION: " + e.getMessage());

    } catch (InvalidFormatException ex) {
        Logger.getLogger(XLSXhandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:magicware.scm.redmine.tools.IssueSyncApp.java

License:Apache License

public void execute(SyncItem syncItem) throws IOException, InvalidFormatException {

    FileInputStream in = null;/* www. j  a  va 2s.c o  m*/

    try {

        // ?JSON??
        String issueTemplate = FileUtils.readFileAsString(syncItem.getJsonTemplate());

        // ???
        Matcher m = Pattern.compile(Constants.ISSUE_FIELD_VALUE_EXP).matcher(issueTemplate);

        List<MatchResult> mrList = new ArrayList<MatchResult>();

        while (m.find()) {
            MatchResult mr = m.toMatchResult();
            mrList.add(mr);
        }

        // ????
        in = new FileInputStream(syncItem.getFilePath());
        Workbook wb = WorkbookFactory.create(in);

        FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

        Sheet sheet = wb.getSheet(syncItem.getSheetName());
        Row row = null;
        Cell cell = null;

        List<String> issues = new ArrayList<String>();

        // ?????
        for (int i = sheet.getLastRowNum(); i >= (syncItem.getKeyRowBeginIdx() > 0
                ? (syncItem.getKeyRowBeginIdx() - 1)
                : 0); i--) {
            // ????
            row = sheet.getRow(i);

            if (row != null) {

                String keyNo = ExcelUtils.getCellContent(row.getCell(syncItem.getKeyColumnIdx() - 1),
                        evaluator);

                // ??????????
                if (StringUtils.isBlank(keyNo)) {
                    break;
                }

                // ????
                if (redmineClient.queryIssue(syncItem.getProjectId(), syncItem.getKeyFiledId(), keyNo) == 0) {
                    StringBuilder newIssue = new StringBuilder();
                    int eolIdx = 0;
                    for (MatchResult matchResult : mrList) {

                        newIssue.append(issueTemplate.substring(eolIdx, matchResult.start()));

                        int cellIndex = Integer.valueOf(matchResult.group(1)) - 1;
                        cell = row.getCell(cellIndex);
                        String cellvalue = ExcelUtils.getCellContent(cell, evaluator);

                        // ?
                        String valueMapStr = matchResult.group(3);
                        Map<String, String> valueMap = null;
                        if (valueMapStr != null) {
                            valueMap = JSON.decode(valueMapStr);
                            if (StringUtils.isNotEmpty(cellvalue) && valueMap.containsKey(cellvalue)) {
                                cellvalue = valueMap.get(cellvalue);
                            } else {
                                cellvalue = valueMap.get("default");
                            }
                        }

                        if (StringUtils.isNotEmpty(cellvalue)) {
                            cellvalue = StringEscapeUtils.escapeJavaScript(cellvalue);
                            newIssue.append(cellvalue);
                        }
                        eolIdx = matchResult.end();
                    }
                    newIssue.append(issueTemplate.substring(eolIdx));
                    issues.add(newIssue.toString());
                } else {
                    // ???
                    break;
                }
            }
        }

        for (int i = issues.size() - 1; i >= 0; i--) {
            Map<String, Issue> issueMap = JSON.decode(issues.get(i));
            log.debug("create new issue >>>");
            log.debug(JSON.encode(issueMap, true));
            redmineClient.createNewIssue(issues.get(i));
        }

    } finally {
        if (in != null) {
            in.close();
            in = null;
        }
    }
}

From source file:main.DataAppender.java

License:RPL License

public static void main(String[] args) {
    String[] toAppend = { "Acres", "Area", "Population", "Employment", "Housing", "Drive Time",
            "Transit Duration", "Walk Time", "Walk Distance" };

    try {//from w ww  . ja v  a  2  s .c  o  m
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
    }

    append_combo = new JComboBox(toAppend);

    //Have the user select the directory where the original TAZ xml files are stored
    JFileChooser choose = new JFileChooser();
    choose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int choice = choose.showOpenDialog(null);
    String path;
    tazForCombo = new ArrayList<String>();
    if (choice == JFileChooser.APPROVE_OPTION) {
        path = choose.getSelectedFile().getPath();

        File dir = new File(path);
        File[] files = dir.listFiles(new XMLFilter());

        localTaz = new HashMap<String, TAZ>();

        for (File f : files) {
            String xmlPath = f.getPath();
            TAZ t = new TAZ(xmlPath);
            localTaz.put(t.getTAZ(), t);
            tazForCombo.add(t.getTAZ() + "");
        }
    }

    ////////////   GUI WORK   /////////////////
    taz_combo = new JComboBox(tazForCombo.toArray());

    excel_directory = new JTextField(10);
    excel_directory.addMouseListener(new MouseListener() {
        public void mouseClicked(MouseEvent e) {
            JFileChooser choose = new JFileChooser();

            int choice = choose.showOpenDialog(null);
            if (choice == JFileChooser.APPROVE_OPTION) {
                excel_directory.setText(choose.getSelectedFile().getPath());
            }
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }
    });

    System.out.println("Files loaded");

    JFrame mainFrame = new JFrame();
    JPanel mainPanel = new JPanel();

    JPanel forCombo = new JPanel();
    final JPanel forTAZ = new JPanel();
    JPanel forDirectory = new JPanel();

    JButton submit = new JButton("Submit");

    forCombo.setLayout(new FlowLayout());
    forTAZ.setLayout(new FlowLayout());
    forDirectory.setLayout(new FlowLayout());

    forCombo.add(new JLabel("Data to Alter: "));
    forTAZ.add(new JLabel("TAZ to Alter: "));
    forDirectory.add(new JLabel("Excel File: "));

    append_combo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (append_combo.getSelectedIndex() < 5)
                taz_combo.setEnabled(false);
            else
                taz_combo.setEnabled(true);

        }
    });

    forCombo.add(append_combo);
    forTAZ.add(taz_combo);
    forDirectory.add(excel_directory);

    forTAZ.setEnabled(false);

    submit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            HashMap<String, Double> vals = new HashMap<String, Double>();

            try {

                //Opens excel workbook and extracts information from first two columns
                InputStream inp = new FileInputStream(excel_directory.getText());
                HSSFWorkbook wb = (HSSFWorkbook) WorkbookFactory.create(inp);
                int row = 0;
                Sheet sheet = wb.getSheetAt(0);
                while (sheet.getRow(row) != null) {
                    int taz = (int) sheet.getRow(row).getCell(0).getNumericCellValue();
                    double val = sheet.getRow(row).getCell(1).getNumericCellValue();
                    vals.put(taz + "", val);
                    row++;
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("Excel Failed");
                System.exit(0);
            }

            //Appends the data based on the combo box selection
            switch (append_combo.getSelectedIndex()) {
            case 0:
                for (String tz : vals.keySet()) {
                    TAZ loc = localTaz.get(tz);
                    loc.setAcres(vals.get(tz));
                    try {
                        loc.toXML("C:/testingAmmendment/");
                    } catch (IOException e1) {
                        System.out.println("Failed To Output");
                    }
                }
                break;
            case 1:

                for (String tz : vals.keySet()) {
                    TAZ loc = localTaz.get(tz);
                    loc.setArea(vals.get(tz));
                    try {
                        loc.toXML("C:/testingAmmendment/");
                    } catch (IOException e1) {
                        System.out.println("Failed To Output");
                    }
                }
                break;

            /////////////////////////BY DEFAULT THE YEAR 2010 IS USED FOR POPULATION, HOUSING, and EMPLOYMENT////////////////////////////////
            case 2:
                System.out.println("Population");
                for (String tz : vals.keySet()) {
                    TAZ loc = localTaz.get(tz);
                    HashMap<Integer, Double> population = new HashMap<Integer, Double>();
                    population.put(2010, vals.get(tz));
                    loc.addPopulationData(population);
                    try {
                        loc.toXML("C:/testingAmmendment/");
                    } catch (IOException e1) {
                        System.out.println("Failed To Output");
                    }
                }
                break;
            case 3:
                System.out.println("Employment");
                for (String tz : vals.keySet()) {
                    TAZ loc = localTaz.get(tz);
                    HashMap<Integer, Double> employment = new HashMap<Integer, Double>();
                    employment.put(2010, vals.get(tz));
                    loc.addEmploymentData(employment);
                    try {
                        loc.toXML("C:/testingAmmendment/");
                    } catch (IOException e1) {
                        System.out.println("Failed To Output");
                    }
                }
                break;
            case 4:
                System.out.println("Housing");

                for (String tz : vals.keySet()) {
                    TAZ loc = localTaz.get(tz);
                    HashMap<Integer, Double> housing = new HashMap<Integer, Double>();
                    housing.put(2010, vals.get(tz));
                    loc.addHousingData(housing);
                    try {
                        loc.toXML("C:/testingAmmendment/");
                    } catch (IOException e1) {
                        System.out.println("Failed To Output");
                    }
                }
                break;
            case 5:
                TAZ loc = localTaz.get(Integer.parseInt(tazForCombo.get(taz_combo.getSelectedIndex())));
                for (String tz : vals.keySet()) {
                    loc.setDriveTime(tz, vals.get(tz));
                }
                try {
                    loc.toXML("C:/testingAmmendment/");
                } catch (IOException e1) {
                    System.out.println("Failed To Output");
                }

                break;
            case 6:
                System.out.println(tazForCombo.get(taz_combo.getSelectedIndex()));
                TAZ curr = localTaz.get(Integer.parseInt(tazForCombo.get(taz_combo.getSelectedIndex())));
                System.out.println("CURRENT: " + curr.getTAZ());
                for (String tz : vals.keySet()) {
                    System.out.println("ITERATING");
                    curr.setTransitDuration(tz, vals.get(tz).longValue());
                }
                try {
                    curr.toXML("C:/testingAmmendment/");
                } catch (IOException e1) {
                    System.out.println("Failed To Output");
                }

                break;
            case 7:
                TAZ fTime = localTaz.get(Integer.parseInt(tazForCombo.get(taz_combo.getSelectedIndex())));
                for (String tz : vals.keySet())
                    fTime.setWalkTime(tz, vals.get(tz).longValue());
                try {
                    fTime.toXML("C:/testingAmmendment/");
                } catch (IOException e1) {
                    System.out.println("Failed To Output");
                }

                break;
            case 8:
                TAZ fDist = localTaz.get(Integer.parseInt(tazForCombo.get(taz_combo.getSelectedIndex())));
                for (String tz : vals.keySet())
                    fDist.setWalkDistance(tz, vals.get(tz));
                try {
                    fDist.toXML("C:/testingAmmendment/");
                } catch (IOException e1) {
                    System.out.println("Failed To Output");
                }

                break;
            default:
                break;

            }
            JOptionPane.showMessageDialog(null, "Alterations Completed");
        }
    });

    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    mainPanel.add(forCombo);
    mainPanel.add(forTAZ);
    mainPanel.add(forDirectory);
    mainPanel.add(submit);

    mainFrame.setTitle("Configuration");
    mainFrame.add(mainPanel);
    mainFrame.pack();
    mainFrame.setLocationRelativeTo(null);
    mainFrame.setVisible(true);
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

From source file:main.KeywordList.java

public void writeToExcel(String fileName) {
    final int GROUP = 0;
    final int PACKAGENAME = 1;
    final int SUBPACKAGENAME = 2;
    final int POSITIONTYPE = 3;
    final int KEYWORD = 4;
    final int DATE = 5;
    final int PRIORITY = 6;

    try {//  www .j  av a  2s  .co  m
        System.out.println("Writing XML: " + fileName);
        ForcastUi.consoleLog("Writing XML: " + fileName);

        FileInputStream fileIn = new FileInputStream(fileName);

        Workbook wb = WorkbookFactory.create(fileIn);
        Sheet sheet = wb.getSheetAt(0);

        keywordList.stream().filter(key -> key.isUsed()).forEach(keyword -> {
            //?  ? or Don't
            int rowInt = 1;
            while (true) {
                Row row = sheet.getRow(rowInt);

                if (row == null)
                    break;

                Cell cellKeyword = row.getCell(KEYWORD);
                String shortName = cellKeyword.getRichStringCellValue().getString();
                if (shortName.equalsIgnoreCase(keyword.getKeyword())) {//If Match, Update Date
                    Cell cellDate = row.getCell(DATE);
                    cellDate.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cellDate.setCellValue(new Date());
                    //cellDate.setCellValue(ForcastUi.dateToString(new Date()));
                    //cellDate.setCellType(Cell.CELL_TYPE_STRING);
                    //cellDate.setCellValue(ForcastUi.dateToString(new Date()));
                    //break;
                }
                rowInt++;
            }
        });

        // Write the output to a file
        FileOutputStream fileOut = new FileOutputStream(fileName);
        wb.write(fileOut);
        fileOut.close();
        fileIn.close();

    } catch (FileNotFoundException e) {
        ErrorMessages.printErrorMsg(ErrorMessages.FILENOTFOUND, fileName);
        ForcastUi.consoleLog(e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        ErrorMessages.printErrorMsg(ErrorMessages.FILECOR, fileName);
        ForcastUi.consoleLog(e.getMessage());
        e.printStackTrace();
    } catch (Exception ex) {
        ErrorMessages.printErrorMsg(ErrorMessages.FILECOR, fileName);
        ForcastUi.consoleLog(ex.getMessage());
        Logger.getLogger(TopStockDescriptionList.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:massiveanalyserxryv2.ServiceTaskSearch.java

@Override
protected Task createTask() {
    Task task;/*from  ww  w  . ja v a2 s.c  om*/
    task = new Task() {
        @Override
        protected Object call() throws Exception {
            // rcupration de la liste des mots cls
            // si il s'agit d'une base de donne slectionn dans la liste
            String path;
            if (modelDataSearch.getAbosoluthPathDb() == null) {
                path = System.getProperty("user.dir");
                path = path + "/db/";
                path = path + modelDataSearch.getNameDb();
            } else {
                // sinon on cre le path avec le chemin absolu (fichier import)
                path = modelDataSearch.getAbosoluthPathDb();
            }

            ArrayList<String> keyWords = new ArrayList<String>();
            keyWords.clear();
            // lecture
            for (String line : Files.readAllLines(Paths.get(path))) {
                keyWords.add(line);
            }

            // rcupration de la liste des contents du tableau excel
            Workbook book = WorkbookFactory.create(modelDataSearch.getFile());
            // rcupration du sheet
            Sheet sheet = book.getSheet(modelDataSearch.getNameSheet());
            // rcupration de la colonne
            int top = sheet.getFirstRowNum();
            int down = sheet.getLastRowNum();
            Row row = sheet.getRow(top);
            // on parse les column jusqu'a ce que le nom soit le meme que celui dans le modele
            short start = row.getFirstCellNum();
            short end = row.getLastCellNum();
            int indiceColumn = -1;
            for (short i = start; i <= end; i++) {
                if (row.getCell(i).getStringCellValue().equals(modelDataSearch.getNameColumn())) {
                    // on connait l'indice de column
                    indiceColumn = i;
                    break;
                }
            }

            // cration de la liste des contents
            ArrayList<DataContent> listContent = new ArrayList<DataContent>();
            listContent.clear();
            for (int j = top; j <= down; j++) {
                if (sheet.getRow(j) != null) {
                    if ((sheet.getRow(j).getCell(indiceColumn).getCellType() == CellType.STRING.getCode())) {
                        DataContent data = new DataContent(j,
                                sheet.getRow(j).getCell(indiceColumn).getStringCellValue());
                        listContent.add(data);
                    }
                }
            }

            // recherches
            for (DataContent content : listContent) {
                for (String key : keyWords) {
                    if (key.isEmpty())
                        continue;

                    int res = content.getContent().toLowerCase().indexOf(key.toLowerCase());
                    if (res != -1) {
                        DataResultat data = new DataResultat(content.getNumRow() + 1, content.getContent(),
                                key); // +1 car dans le fichie excel les row commence  1 et pas  0
                        ob.add(data);
                    }
                }
            }

            // Fermeture du workbook
            if (book != null)
                book.close();
            //tableauResultat.setItems(ob);
            return (Object) ob;

        }

    };

    return task;
}

From source file:math.page.KnapsackTest.java

License:Apache License

public static void test3() throws InvalidFormatException, IOException {
    String path = "d:" + File.separator + "price.xlsx";
    File file = new File(path);
    Workbook workbook = WorkbookFactory.create(file);
    Sheet sheet = workbook.getSheetAt(0);
    List<Knapsack> bags = new ArrayList<Knapsack>();
    try {//from  w ww .  jav a  2s.c om
        for (int row = 1; row <= sheet.getLastRowNum(); row++) {
            Row row2 = sheet.getRow(row);
            Cell cell0 = row2.getCell(0);
            Cell cell1 = row2.getCell(1);
            // 
            // System.out.print(cell.toString() + "  ");
            // System.out.println(cell0.getCellComment().toString());

            // Integer integer = Double.valueOf(cell0.getNumericCellValue())
            // .intValue();
            Integer integer = null;
            switch (cell0.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell0)) {

                } else {
                    cell0.setCellType(Cell.CELL_TYPE_STRING);
                    String temp = cell0.getStringCellValue();
                    // ??????????Double
                    if (temp.indexOf(".") > -1) {
                        integer = Double.valueOf(temp).intValue();
                    } else {
                        integer = Integer.valueOf(temp).intValue();
                    }
                }
                break;
            case Cell.CELL_TYPE_STRING:
                integer = Integer.valueOf(cell0.getStringCellValue()).intValue();
                break;
            default:
                break;
            }
            Knapsack knapsack = new Knapsack(integer, integer);
            knapsack.setNo(Double.valueOf(cell1.getNumericCellValue()).intValue());

            bags.add(knapsack);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    List<Total> list = test4();

    write(list, bags);

}

From source file:math.page.KnapsackTest.java

License:Apache License

public static List<Total> test4() throws InvalidFormatException, IOException {
    String path = "d:" + File.separator + "total.xlsx";
    File file = new File(path);
    // Workbook workbook = Workbook.getWorkbook(file);
    Workbook workbook = WorkbookFactory.create(file);
    // Sheet sheet = workbook.getSheet(0);
    Sheet sheet = workbook.getSheetAt(0);
    List<Total> bags = new ArrayList<Total>();
    try {//www .  j a  v a 2  s .c o  m

        for (int row = 1; row <= sheet.getLastRowNum(); row++) {
            // Cell[] cells = sheet.getRow(row);
            // System.out.println(cells[0].getContents());
            Row row2 = sheet.getRow(row);
            Cell cell0 = row2.getCell(0);
            Cell cell1 = row2.getCell(1);
            Integer integer = null;
            switch (cell0.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell0)) {

                } else {
                    cell0.setCellType(Cell.CELL_TYPE_STRING);
                    String temp = cell0.getStringCellValue();
                    // ??????????Double
                    if (temp.indexOf(".") > -1) {
                        integer = Double.valueOf(temp).intValue();
                    } else {
                        integer = Integer.valueOf(temp).intValue();
                    }
                }
                break;
            case Cell.CELL_TYPE_STRING:
                integer = Integer.valueOf(cell0.getStringCellValue()).intValue();
                break;
            default:
                break;
            }

            Total total = new Total();
            total.setNo(Double.valueOf(cell1.getNumericCellValue()).intValue());
            total.setTotal(integer);
            bags.add(total);
        }
        Arrays.sort(bags.toArray());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return bags;
}

From source file:metrics.sink.MetricsTable.java

License:Open Source License

private void init(File output, boolean preserveExistingWorkbook)
        throws InvalidFormatException, FileNotFoundException, IOException {
    if (!output.exists())
        output.createNewFile();//  w  w w .  ja va 2 s .  co  m
    if (preserveExistingWorkbook)
        try {
            workBook = WorkbookFactory.create(new FileInputStream(output));
        } catch (IllegalArgumentException ex) {

        }
    if (workBook == null)
        workBook = new HSSFWorkbook();
    this.currentSheet = workBook.createSheet();
}