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

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

Introduction

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

Prototype

void write(OutputStream stream) throws IOException;

Source Link

Document

Write out this workbook to an Outputstream.

Usage

From source file:org.apache.ranger.biz.ServiceDBStore.java

License:Apache License

private void writeExcel(List<RangerPolicy> policies, String excelFileName, HttpServletResponse response)
        throws IOException {
    Workbook workbook = null;
    OutputStream outStream = null;
    try {/*from   ww w.j  a v a  2s .  c  o  m*/
        workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        createHeaderRow(sheet);
        int rowCount = 0;
        if (!CollectionUtils.isEmpty(policies)) {
            for (RangerPolicy policy : policies) {
                long serviceType = daoMgr.getXXService().findByName(policy.getService()).getType();
                List<RangerPolicyItem> policyItems = policy.getPolicyItems();
                List<RangerRowFilterPolicyItem> rowFilterPolicyItems = policy.getRowFilterPolicyItems();
                List<RangerDataMaskPolicyItem> dataMaskPolicyItems = policy.getDataMaskPolicyItems();

                if (CollectionUtils.isNotEmpty(policyItems)) {
                    for (RangerPolicyItem policyItem : policyItems) {
                        Row row = sheet.createRow(++rowCount);
                        writeBookForPolicyItems(policy, policyItem, null, null, row);
                    }
                } else if (CollectionUtils.isNotEmpty(dataMaskPolicyItems)) {
                    for (RangerDataMaskPolicyItem dataMaskPolicyItem : dataMaskPolicyItems) {
                        Row row = sheet.createRow(++rowCount);
                        writeBookForPolicyItems(policy, null, dataMaskPolicyItem, null, row);
                    }
                } else if (CollectionUtils.isNotEmpty(rowFilterPolicyItems)) {
                    for (RangerRowFilterPolicyItem rowFilterPolicyItem : rowFilterPolicyItems) {
                        Row row = sheet.createRow(++rowCount);
                        writeBookForPolicyItems(policy, null, null, rowFilterPolicyItem, row);
                    }
                } else if (serviceType == 100) {
                    Row row = sheet.createRow(++rowCount);
                    writeBookForTag(policy, row);
                }
            }
        }
        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        workbook.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0");
        response.setHeader("Content-Disposition", "attachment; filename=" + excelFileName);
        outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
    } catch (IOException ex) {
        LOG.error("Failed to create report file " + excelFileName, ex);
    } catch (Exception ex) {
        LOG.error("Error while generating report file " + excelFileName, ex);
    } finally {
        if (outStream != null) {
            outStream.close();
        }
        if (workbook != null) {
            workbook.close();
        }
    }
}

From source file:org.ascent.deployment.excel.output.ExcelDeploymentPlan.java

License:Open Source License

public static void write(DeploymentPlan plan, File target) throws IOException {
    try {/*ww w.  j  a v  a 2s . co  m*/

        Workbook workbook = new HSSFWorkbook();

        Sheet sheet = workbook.createSheet(DeploymentPlanHandler.DEPLOYMENT_PLAN_SHEET);

        Component[] comps = plan.getDeploymentConfiguration().getComponents();
        Node[] nodes = plan.getDeploymentConfiguration().getNodes();

        Map<Node, Integer> indices = new HashMap<Node, Integer>();
        for (int i = 0; i < nodes.length; i++) {
            indices.put(nodes[i], i + 1);

            Cell c = get(sheet, 0, i + 1, Cell.CELL_TYPE_STRING);
            c.setCellValue(nodes[i].getLabel());
        }

        for (int i = 0; i < comps.length; i++) {

            Component c = comps[i];
            Cell cell = get(sheet, i + 1, 0, Cell.CELL_TYPE_STRING);
            cell.setCellValue(c.getLabel());

            Cell dc = get(sheet, i + 1, indices.get(plan.getHost(c)), Cell.CELL_TYPE_NUMERIC);
            dc.setCellValue(1);
        }

        FileOutputStream fout = new FileOutputStream(target);

        workbook.write(fout);
        fout.flush();
        fout.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.bbreak.excella.core.util.PoiUtil.java

License:Open Source License

/**
 * ?????/*from ww w . j  a v a  2 s . c  o  m*/
 * 
 * @param workbook 
 * @param filename ??
 * @throws IOException ????
 */
public static void writeBook(Workbook workbook, String filename) throws IOException {
    // 
    FileOutputStream fileOut = new FileOutputStream(filename);
    try {
        workbook.write(fileOut);
    } finally {
        fileOut.close();
    }
}

From source file:org.bbreak.excella.reports.exporter.ExcelOutputStreamExporter.java

License:Open Source License

@Override
public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration)
        throws ExportException {
    try {/*from ww  w.j  a  v  a2 s  .  co  m*/
        if (log.isInfoEnabled()) {
            log.info("??" + outputStream.getClass().getCanonicalName() + "????");
        }
        book.write(outputStream);
    } catch (IOException e) {
        throw new ExportException(e);
    }
}

From source file:org.bonitasoft.connectors.excel.AddDimensionedImage.java

License:Apache License

/**
 * The main entry point to the program. It contains code that demonstrates
 * one way to use the program./*  w  w  w  . j  a  v a2  s . c  o m*/
 *
 * Note, the code is not restricted to use on new workbooks only. If an
 * image is to be inserted into an existing workbook. just open that
 * workbook, gat a reference to a sheet and pass that;
 *
 *      AddDimensionedImage addImage = new AddDimensionedImage();
 *
 *      File file = new File("....... Existing Workbook .......");
 *      FileInputStream fis = new FileInputStream(file);
 *      Workbook workbook = new HSSFWorkbook(fis);
 *      HSSFSheet sheet = workbook.getSheetAt(0);
 *      addImage.addImageToSheet("C3", sheet, "image.jpg", 30, 20,
 *          AddDimensionedImage.EXPAND.ROW);
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    String imageFile = null;
    String outputFile = null;
    FileOutputStream fos = null;
    Workbook workbook = null;
    Sheet sheet = null;
    try {
        if (args.length < 2) {
            System.err.println("Usage: AddDimensionedImage imageFile outputFile");
            return;
        }
        workbook = new HSSFWorkbook();
        sheet = workbook.createSheet("Picture Test");
        // Note that as the code has been ported to the SS model, the following
        // would be equally as valid - workbook = new XSSFWorkbook();
        imageFile = args[0];
        outputFile = args[1];
        new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(),
                new File(imageFile).toURI().toURL(), 100, 40, AddDimensionedImage.EXPAND_ROW_AND_COLUMN);
        fos = new FileOutputStream(outputFile);
        workbook.write(fos);
    } catch (FileNotFoundException fnfEx) {
        System.out.println("Caught an: " + fnfEx.getClass().getName());
        System.out.println("Message: " + fnfEx.getMessage());
        System.out.println("Stacktrace follows...........");
        fnfEx.printStackTrace(System.out);
    } catch (IOException ioEx) {
        System.out.println("Caught an: " + ioEx.getClass().getName());
        System.out.println("Message: " + ioEx.getMessage());
        System.out.println("Stacktrace follows...........");
        ioEx.printStackTrace(System.out);
    } finally {
        if (fos != null) {
            try {
                fos.close();
                fos = null;
            } catch (IOException ioEx) {
                // I G N O R E
            }
        }
    }
}

From source file:org.centralperf.helper.view.AbstractPOIExcelView.java

License:Open Source License

@Override
protected final void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Workbook workbook = null;

    if (url != null) {
        workbook = getTemplateSource(url, request);
    } else {//from   w  w  w .  j a v a  2  s  . c o m
        workbook = createWorkbook();
    }

    if (workbook instanceof XSSFWorkbook) {
        setContentType(CONTENT_TYPE_XLSX);
    } else {
        setContentType(CONTENT_TYPE_XLS);
    }

    buildExcelDocument(model, workbook, request, response);

    // Set the content type.
    response.setContentType(getContentType());

    // Flush byte array to servlet output stream.
    ServletOutputStream out = response.getOutputStream();
    out.flush();
    // Have to catch exception because of thise bug : https://issues.apache.org/bugzilla/show_bug.cgi?id=49940
    try {
        workbook.write(out);
    } catch (org.apache.xmlbeans.impl.values.XmlValueDisconnectedException disconnectedException) {
        // Do nothing... In fact, it's only a bug...
    }
    out.flush();

    // Don't close the stream - we didn't open it, so let the container
    // handle it.
    // http://stackoverflow.com/questions/1829784/should-i-close-the-servlet-outputstream
}

From source file:org.centralperf.helper.view.ExcelOOXMLView.java

License:Open Source License

/**
 * @see AbstractPOIExcelView#buildExcelDocument(Map, Workbook, HttpServletRequest, HttpServletResponse)
 *//*from   www .j av a 2 s.  c o  m*/
@Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    log.debug("Generating Excel report from run samples");

    // Set the headers
    response.setHeader("Content-Type", "application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=central_perf_result.xlsx");

    // get data model which is passed by the Spring container
    Run run = (Run) model.get("run");

    // Set run summary informations
    setCellValueByName(PROJECT_NAME_CELL_NAME, run.getProject().getName(), workbook);
    setCellValueByName(RUN_LABEL_CELL_NAME, run.getLabel(), workbook);
    setCellValueByName(RUN_DESCRIPTION_CELL_NAME, run.getComment(), workbook);
    setCellValueByName(START_DATE_CELL_NAME, run.getStartDate().toString(), workbook);
    setCellValueByName(START_DATE_CELL_NAME, run.getStartDate().toString(), workbook);
    setCellValueByName(GENERATED_ON_CELL_NAME, "" + unixTimestamp2ExcelTimestampconvert(new Date().getTime()),
            workbook);

    // Populate data sheet
    XSSFSheet dataSheet = (XSSFSheet) workbook.getSheet(DATA_SHEET_NAME);
    // Set date style for first column
    CellStyle dateStyle = workbook.createCellStyle();
    CreationHelper createHelper = workbook.getCreationHelper();
    dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy/mm/dd"));
    dataSheet.setDefaultColumnStyle(0, dateStyle);

    // Add samples
    for (int i = 0; i < run.getSamples().size(); i++) {
        Sample sample = run.getSamples().get(i);
        XSSFRow dataRow = dataSheet.createRow(i + 1);
        if (sample.getTimestamp() != null) {
            dataRow.createCell(0)
                    .setCellValue(unixTimestamp2ExcelTimestampconvert(sample.getTimestamp().getTime()));
            dataRow.createCell(1).setCellValue(sample.getElapsed());
            dataRow.createCell(2).setCellValue(sample.getSampleName());
            dataRow.createCell(3).setCellValue(sample.getStatus());
            dataRow.createCell(4).setCellValue(sample.getReturnCode());
            dataRow.createCell(5).setCellValue(sample.getSizeInOctet());
            dataRow.createCell(6).setCellValue(sample.getGrpThreads());
            dataRow.createCell(7).setCellValue(sample.getAllThreads());
            dataRow.createCell(8).setCellValue(sample.getLatency());
        }
    }

    // Return generated sheet
    OutputStream outStream = null;
    try {
        outStream = response.getOutputStream();
        workbook.write(outStream);
        outStream.flush();
    } finally {
        outStream.close();
    }

}

From source file:org.cerberus.service.export.ExportServiceFactory.java

License:Open Source License

private Answer exportToXLS() {
    Answer ans = new Answer();

    //Blank workbook
    Workbook workbook = new XSSFWorkbook();

    if (data.equals("TestCaseWithExecution")) {
        createReportByTagExport(workbook);
    }//from   www. j  a  v  a2  s.  co m

    FileOutputStream outputStream;
    try {
        String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
        outputStream = new FileOutputStream(this.fileName + "_" + timeStamp + type.getFileExtension());
        try {
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (IOException ex) {
            Logger.getLogger(ExportServiceFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ExportServiceFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    //each country will be a page in the xls file
    return ans;
}

From source file:org.citydb.plugins.spreadsheet_gen.controller.SpreadsheetExporter.java

License:Open Source License

public void convertToXSLX(String csvPath, String path, String filename) throws Exception {
    // convert csv to excel
    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("Countries");
    CsvReader reader = null;/*from  ww w  . ja va 2  s . c  o  m*/

    int rowIndex = 0;

    String xlsxFullpath = path + File.separator + filename + ".xlsx";

    reader = new CsvReader(csvPath, SeparatorPhrase.getInstance().getIntoCloudDefaultSeperator().charAt(0),
            Charset.forName("UTF-8"));

    // avoid error message of CsvReader in case of column lengths greater than 100,000 characters
    reader.setSafetySwitch(false);

    reader.readRecord();
    String[] spshColumnNames = reader.getValues();
    Row row = sheet.createRow(rowIndex);
    for (int i = 0; i < spshColumnNames.length; i++) {
        Cell cell = row.createCell(i);
        cell.setCellValue(spshColumnNames[i]);
    }
    rowIndex++;
    Map<String, String> templateMap = Translator.getInstance().getTemplateHashmap();

    try {
        while (reader.readRecord()) {
            row = sheet.createRow(rowIndex);
            String[] valueArray = reader.getValues();
            if (valueArray != null && valueArray.length > 0) {
                for (int i = 0; i < valueArray.length; i++) {
                    if (valueArray[i] != null && String.valueOf(valueArray[i].trim()).length() > 0) {
                        String dbTableColumn = templateMap.get(spshColumnNames[i]);
                        Cell cell = row.createCell(i);
                        int dataType = Util._3DCITYDB_TABLES_AND_COLUMNS.get(dbTableColumn);
                        if (dataType == Util.NUMBER_COLUMN_VALUE) {
                            try {
                                cell.setCellValue(Double.valueOf(valueArray[i]));
                            } catch (NumberFormatException nfe) {
                                cell.setCellValue(String.valueOf(valueArray[i]));
                            }
                        } else {
                            cell.setCellValue(String.valueOf(valueArray[i]));
                        }
                    }
                }
                rowIndex++;
            }
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    reader.close();

    // lets write the excel data to file now
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(new File(xlsxFullpath));
        workbook.write(fos);
        fos.close();
    } catch (IOException ioe) {
        logController.error(ioe.getMessage());
        shouldRun = false;
    }

}

From source file:org.controldepersonal.excel.ConexionExcel.java

public void exportaExcel() {
    try {//from  ww w  . ja  v a  2 s.c om
        File archivoXLSX = new File(rutaArchivo);
        if (archivoXLSX.exists())
            archivoXLSX.delete();
        archivoXLSX.createNewFile();
        Workbook libro = new HSSFWorkbook();
        FileOutputStream archivo = new FileOutputStream(archivoXLSX);
        Sheet hoja = libro.createSheet("Exportacin de SGCP");
        /*for(int f=0;f<10;f++){
        Row fila = hoja.createRow(f);
        for(int c=0;c<5;c++){
        Cell celda = fila.createCell(c);
        }
        }*/
        //Escribir en celdas
        /*
        celda.setCellValue("Encabezado #"+c);
        */
        for (int i = 0; i < 1; i++) {
            Row fila = hoja.createRow(i);
            for (int c = 0; c < 2; c++) {
                Cell celda = fila.createCell(c);
                if (i == 0 && c == 0) {
                    celda.setCellValue("Valor 1");
                }
            }
        }
        libro.write(archivo);
        archivo.close();
        Desktop.getDesktop().open(archivoXLSX);
    } catch (IOException ex) {
        Logger.getLogger(ConexionExcel.class.getName()).log(Level.SEVERE, null, ex);
    }
}