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

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

Introduction

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

Prototype

@Override
public XSSFSheet createSheet(String sheetname) 

Source Link

Document

Create a new sheet for this Workbook and return the high level representation.

Usage

From source file:nl.architolk.ldt.processors.ExcelSerializer.java

License:Open Source License

protected void readInput(final PipelineContext pipelineContext, final ProcessorInput input, Config config,
        OutputStream outputStream) {

    try {/*from  www .ja  v a 2 s  . co  m*/
        // Read the input as a DOM
        final Document domDocument = readInputAsDOM(pipelineContext, input);

        // create workbook (xlsx)
        XSSFWorkbook wb = new XSSFWorkbook();

        //iterate through sheets;
        NodeList sheetNodes = domDocument.getElementsByTagName("sheet");

        if (sheetNodes.getLength() == 0) {
            throw new OXFException("At least one sheet should be present");
        }

        for (short i = 0; i < sheetNodes.getLength(); i++) {
            Node sheetNode = sheetNodes.item(i);
            if (sheetNode.getNodeType() == Node.ELEMENT_NODE) {
                Element sheetElement = (Element) sheetNode;
                XSSFSheet sheet = wb.createSheet(sheetElement.getAttribute("name"));

                //iterate through rows;
                NodeList rowNodes = sheetNode.getChildNodes();
                short rownr = 0;
                for (short r = 0; r < rowNodes.getLength(); r++) {
                    Node rowNode = rowNodes.item(r);
                    if (rowNode.getNodeType() == Node.ELEMENT_NODE) {
                        XSSFRow row = sheet.createRow(rownr++);

                        //iterate through columns;
                        NodeList columnNodes = rowNode.getChildNodes();
                        short colnr = 0;
                        for (short c = 0; c < columnNodes.getLength(); c++) {
                            Node columnNode = columnNodes.item(c);
                            if (columnNode.getNodeType() == Node.ELEMENT_NODE) {
                                XSSFCell cell = row.createCell(colnr++);
                                cell.setCellValue(columnNode.getTextContent());
                            }
                        }
                    }
                }
            }
        }

        // write workbook to stream
        wb.write(outputStream);
        outputStream.close();

    } catch (Exception e) {
        throw new OXFException(e);
    }

}

From source file:nl.b3p.viewer.admin.stripes.ServiceUsageMatrixActionBean.java

License:Open Source License

public static XSSFWorkbook createWorkBook(String theXml) throws ParserConfigurationException, SAXException,
        IOException, XPathExpressionException, XPathFactoryConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(theXml)));

    XSSFWorkbook workbook = new XSSFWorkbook();
    String tempProperty = null;/*from www . ja v  a 2  s  .  c  om*/
    try {
        Element root = doc.getDocumentElement();
        /* JSTL XML is setting the system property to use the jstl xpath facotry.
         * Remove the setting temporary:
         * see: https://java.net/jira/browse/JSTL-1
         */
        tempProperty = System
                .getProperty(XPathFactory.DEFAULT_PROPERTY_NAME + ":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI);
        if (tempProperty != null) {
            System.clearProperty(
                    XPathFactory.DEFAULT_PROPERTY_NAME + ":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI);
        }

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        XPathExpression exprFeatureSource = xpath.compile("//featureSource");
        XPathExpression exprFeatureType = xpath.compile("featureType");
        XPathExpression exprApplication = xpath.compile("applications/application");
        XPathExpression exprLayer = xpath.compile("layers/layer");
        XPathExpression exprAppLayer = xpath.compile("applayers/applayer");
        XPathExpression exprId = xpath.compile("id/text()");
        XPathExpression exprAlias = xpath.compile("alias/text()");
        XPathExpression exprName = xpath.compile("name/text()");
        XPathExpression exprVersion = xpath.compile("version/text()");
        XPathExpression exprProtocol = xpath.compile("protocol/text()");
        XPathExpression exprUrl = xpath.compile("url/text()");

        XSSFSheet sheet = workbook.createSheet("Sheet 1");
        int rowNum = 0;

        Row head = sheet.createRow(rowNum++);
        String[] headValues = { "Bron", "Featuretype", "Applicatie", "Layernaam van service",
                "Application layer (kaart)" };
        for (int c = 0; c < headValues.length; c++) {
            Cell cell = head.createCell(c);
            cell.setCellValue(headValues[c]);
        }
        List<String> columns = new ArrayList<String>();
        for (int i = 0; i < headValues.length; i++) {
            columns.add("");
        }
        NodeList featureSources = (NodeList) exprFeatureSource.evaluate(root, XPathConstants.NODESET);

        for (int fs = 0; fs < featureSources.getLength(); fs++) {
            Node featureSource = featureSources.item(fs);

            String fsString = (String) exprName.evaluate(featureSource, XPathConstants.STRING);
            fsString += " (" + (String) exprProtocol.evaluate(featureSource, XPathConstants.STRING);
            fsString += ":: " + (String) exprUrl.evaluate(featureSource, XPathConstants.STRING);
            fsString += " id: " + (String) exprId.evaluate(featureSource, XPathConstants.STRING);
            fsString += ")";
            columns.set(0, fsString);
            NodeList featureTypes = (NodeList) exprFeatureType.evaluate(featureSource, XPathConstants.NODESET);
            for (int ft = 0; ft < featureTypes.getLength(); ft++) {
                Node featureType = featureTypes.item(ft);
                //String ftId = (String) exprId.evaluate(featureType,XPathConstants.STRING);
                String ftName = (String) exprName.evaluate(featureType, XPathConstants.STRING);
                //String ftString = ""+ftName;
                columns.set(1, ftName);
                NodeList applications = (NodeList) exprApplication.evaluate(featureType,
                        XPathConstants.NODESET);
                for (int app = 0; app < applications.getLength(); app++) {
                    Node application = applications.item(app);
                    String appVersion = (String) exprVersion.evaluate(application, XPathConstants.STRING);

                    String appString = (String) exprName.evaluate(application, XPathConstants.STRING);
                    if (appVersion != null) {
                        appString += ", version: " + appVersion;
                    }
                    appString += " (" + (String) exprId.evaluate(application, XPathConstants.STRING) + ")";
                    columns.set(2, appString);
                    NodeList layers = (NodeList) exprLayer.evaluate(application, XPathConstants.NODESET);
                    for (int lay = 0; lay < layers.getLength(); lay++) {
                        Node layer = layers.item(lay);
                        String layerString = "";
                        layerString += (String) exprName.evaluate(layer, XPathConstants.STRING);
                        columns.set(3, layerString);
                        NodeList appLayers = (NodeList) exprAppLayer.evaluate(layer, XPathConstants.NODESET);
                        for (int al = 0; al < appLayers.getLength(); al++) {
                            Node appLayer = appLayers.item(al);
                            String alString = (String) exprAlias.evaluate(appLayer, XPathConstants.STRING);
                            alString += " (" + (String) exprId.evaluate(appLayer, XPathConstants.STRING) + ")";
                            columns.set(4, alString);
                            Row row = sheet.createRow(rowNum++);
                            for (int c = 0; c < columns.size(); c++) {
                                Cell cell = row.createCell(c);
                                cell.setCellValue(columns.get(c));
                            }
                        }
                    }
                }
            }
        }
    } finally {
        if (tempProperty != null) {
            System.setProperty(XPathFactory.DEFAULT_PROPERTY_NAME + ":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI,
                    tempProperty);
        }
    }
    return workbook;
}

From source file:nmap.parser.ExcelLayout.java

public void Layouting(String nmap, String folderpath) throws FileNotFoundException, IOException {
    MainList ml = new MainList();
    ml.Mainlist(nmap, folderpath);//ww  w .j av  a  2s .co  m
    //  System.out.println(ml.getHeadertemp());
    //System.out.println(ml.getPopulatefield());

    XSSFWorkbook workbook = new XSSFWorkbook();
    //Create a blank sheet
    XSSFSheet spreadsheet = workbook.createSheet(" PORT STATUS ");
    //Create row object
    XSSFRow row;
    //This data needs to be written (Object[])
    //setHeadertemp(header);
    // setPopulatefield(fieldlayout);
    //    String s = fieldlayout.get(0).toString();
    //System.out.println("MainList class: "+s);
    Map<String, Object[]> empinfo = new TreeMap<String, Object[]>();
    empinfo.put("1", ml.getHeadertemp().toArray());
    int ind = 2;
    //  empinfo.put("2", fieldlayout.get(0).toArray());
    for (int h = 0; h < ml.getPopulatefield().size(); h++) {
        String index = Integer.toString(ind);
        empinfo.put(index, ml.getPopulatefield().get(h).toArray());
        ind++;
    }

    Set<String> keyid = empinfo.keySet();
    int rowid = 0;
    for (String key : keyid) {
        row = spreadsheet.createRow(rowid++);
        Object[] objectArr = empinfo.get(key);
        int cellid = 0;
        for (Object obj : objectArr) {
            XSSFCell cell = row.createCell(cellid++);
            cell.setCellValue((String) obj);
        }
    }
    // Write the workbook in file system
    String hhaha = "Kingkunta.xlsx";
    FileOutputStream out = new FileOutputStream(new File(hhaha));
    workbook.write(out);
    out.close();
    System.out.println(hhaha + ".xlsx written successfully");

}

From source file:Opm_Package.Excell_Dublicating.java

public void createExcel(ArrayList<Object[]> allobj, int number, String excelFilePath, String sheetName)
        throws IOException {
    FileOutputStream fos = null;/*from  ww w . java  2  s  .  c o  m*/
    try {
        XSSFWorkbook workbook = null;
        if (new File(excelFilePath).createNewFile()) {
            workbook = new XSSFWorkbook();
        } else {
            FileInputStream pfs = new FileInputStream(new File(excelFilePath));
            workbook = new XSSFWorkbook(pfs);
        }
        if (workbook.getSheet(sheetName) == null) {
            fos = new FileOutputStream(excelFilePath);
            sheet = workbook.createSheet(sheetName);
            ///
            int rowid2 = sheet.getLastRowNum();
            int x;
            for (x = 0; x < allobj.size(); x++) {//Looping thru the array list to pick the objects...
                rows = sheet.createRow(rowid2++);
                Object[] objectArr = allobj.get(x);
                int cellid = 0;
                for (Object obj : objectArr) {//Looping inside the object...
                    Cell cells = rows.createCell(cellid++);
                    if (obj instanceof String) {
                        cells.setCellValue((String) obj);
                    } else if (obj instanceof Integer) {
                        cells.setCellValue((int) obj);
                    } else if (obj instanceof Double) {
                        cells.setCellValue((double) obj);
                    }
                } // End of for loop for object
            } //End of for loop for arraylist of object....

            workbook.write(fos);
            System.out.println("Excel File Created is : " + excelFilePath + " With sheet name :" + sheetName);
            System.out.println("\n\n");
        }

    } catch (IOException e) {
        throw e;
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}

From source file:optrecursive_testbench.Save.java

public void save(Matrix matrice, String filename) throws FileNotFoundException, IOException { ///It is working
    String dirPath = OptRecursive_Testbench.excelFilePath + File.separator + filepath;
    setupDirectory(dirPath);//from  w ww  . j  a  v a2s .  c om
    String fileName = dirPath + File.separator + filename + ".xlsx";
    System.out.println("Using filepath " + filepath + ", saving to address: " + fileName);
    try {
        FileOutputStream fileOut = new FileOutputStream(fileName);
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet worksheet = workbook.createSheet("POI Worksheet");

        int lastvaluex = matrice.getRowDimension();
        int lastvaluey = matrice.getColumnDimension();
        int ih = 0;
        int jh = 0;

        while (ih < lastvaluex) {

            XSSFRow row = worksheet.createRow(ih);
            ih++;
            while (jh < lastvaluey) {
                XSSFCell cell = row.createCell(jh);
                jh++;
                cell.setCellValue(matrice.get(ih - 1, jh - 1));
            }
            jh = 0;
        }
        workbook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:optrecursive_testbench.Save.java

public void savedouble(double matrice, String filename) throws FileNotFoundException, IOException { ///It is working
    String dirPath = OptRecursive_Testbench.excelFilePath + File.separator + filepath;
    setupDirectory(dirPath);/*from ww w  .j  ava 2s.c o  m*/
    String fileName = dirPath + File.separator + filename + ".xlsx";
    try {
        FileOutputStream fileOut = new FileOutputStream(fileName);
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet worksheet = workbook.createSheet("POI Worksheet");

        int lastvaluex = 1;
        int lastvaluey = 1;
        int ih = 0;
        int jh = 0;

        while (ih < lastvaluex) {

            XSSFRow row = worksheet.createRow(ih);
            ih++;
            while (jh < lastvaluey) {
                XSSFCell cell = row.createCell(jh);
                jh++;
                cell.setCellValue(matrice);
            }
            jh = 0;
        }
        workbook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:optrecursive_testbench.Save.java

public void save3D(Matrix matrice, String filename, int kj) throws FileNotFoundException, IOException { ///It is working
    String dirPath = OptRecursive_Testbench.excelFilePath + File.separator + filepath;
    setupDirectory(dirPath);//from w  w w.j  a  v  a  2 s. c om
    String fileName = dirPath + File.separator + filename + kj + ".xlsx";
    try {
        FileOutputStream fileOut = new FileOutputStream(fileName);
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet worksheet = workbook.createSheet("POI Worksheet");

        int lastvaluex = matrice.getRowDimension();
        int lastvaluey = matrice.getColumnDimension();
        int ih = 0;
        int jh = 0;

        while (ih < lastvaluex) {
            XSSFRow row = worksheet.createRow(ih);
            while (jh < lastvaluey) {
                XSSFCell cell = row.createCell(jh);
                cell.setCellValue(matrice.get(ih, jh));
                jh++;
            }
            ih++;
            jh = 0;
        }
        workbook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:optrecursive_testbench.Save.java

public void saveString(String[] matrice, String filename) throws FileNotFoundException, IOException { ///It is working
    String dirPath = OptRecursive_Testbench.excelFilePath + File.separator + filepath;
    setupDirectory(dirPath);/*from w ww  .  java2  s .c  o m*/
    String fileName = dirPath + File.separator + filename + ".xlsx";
    try {
        FileOutputStream fileOut = new FileOutputStream(fileName);
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet worksheet = workbook.createSheet("POI Worksheet");

        int lastvaluex = matrice.length;
        int lastvaluey = 1;
        int ih = 0;
        int jh = 0;

        while (ih < lastvaluex) {
            XSSFRow row = worksheet.createRow(ih);

            while (jh < lastvaluey) {
                XSSFCell cell = row.createCell(jh);
                cell.setCellValue(matrice[ih]);
                jh++;
            }
            ih++;
            jh = 0;
        }
        workbook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.adimadim.kosu.MainForm.java

private void exportToExcel() throws Exception {
    List<RaceScore> raceScoreList = getRaceService().retrieveRaceScoresByRaceId(selectedRace.getRaceId());
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Sonuclar");
    XSSFRow row = sheet.createRow(0);/* w  w  w .ja  v a2s .com*/
    row.createCell(0).setCellValue("Id");
    row.createCell(1).setCellValue("Gs No");
    row.createCell(2).setCellValue("Ad");
    row.createCell(3).setCellValue("Soyad");
    row.createCell(4).setCellValue("Cinsiyet");
    row.createCell(5).setCellValue("Sra");
    int i = 1;
    for (RaceScore raceScore : raceScoreList) {
        XSSFRow tempRow = sheet.createRow(i);
        tempRow.createCell(0).setCellValue(raceScore.getAccount().getAccountId());
        tempRow.createCell(1).setCellValue(raceScore.getAccount().getChestNumber());
        tempRow.createCell(2).setCellValue(raceScore.getAccount().getName());
        tempRow.createCell(3).setCellValue(raceScore.getAccount().getSurname());
        tempRow.createCell(4).setCellValue(raceScore.getAccount().getGender());
        tempRow.createCell(5).setCellValue(raceScore.getOrderNo());
        i++;
    }
    String fileName = "sonuclar.xlsx";
    try (FileOutputStream fos = new FileOutputStream(fileName)) {
        workbook.write(fos);
    }
    System.out.println(fileName + " written successfully");

}

From source file:org.alfresco.bm.report.XLSXReporter.java

License:Open Source License

/**
 * Creates a new line with values in the sheet.
 * /*  ww w . j  a va 2 s.  c  o m*/
 * @param workbook
 *            (XSSFWorkbook, required) workbook to create the row in
 * @param sheetRow
 *            (XSSFSheetRow, required) sheet to create the data row in
 * @param sheetName
 *            (String, required) name of the sheet
 * @param values
 *            (String [], optional) if null or empty no work will be done, else the values written to the next line
 * @param bold
 *            (boolean) true: the values will be set in bold font face, else normal
 * 
 * @since 2.0.10
 */
private void createSheetRow(XSSFWorkbook workbook, XSSFSheetRow sheetRow, String sheetName, List<String> values,
        boolean bold) {
    if (null != values && values.size() > 0) {
        // check if sheet exists and create if not
        if (null == sheetRow.sheet) {
            sheetRow.sheet = workbook.createSheet(sheetName);
        }

        // create cell style
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);

        if (bold) {
            // Create bold font
            Font fontBold = workbook.createFont();
            fontBold.setBoldweight(Font.BOLDWEIGHT_BOLD);
            cellStyle.setFont(fontBold);
        }

        // create row
        XSSFRow row = sheetRow.sheet.createRow(sheetRow.rowCount++);

        // set values
        for (int i = 0; i < values.size(); i++) {
            row.getCell(i).setCellValue(values.get(i));
            row.getCell(i).setCellStyle(cellStyle);
        }
    }
}