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:com.vaadin.addon.spreadsheet.SpreadsheetFactory.java

License:Open Source License

/**
 * Writes the current Workbook state from the given Spreadsheet to the given
 * file.// w w w  .  j a  v  a2 s.  c  o m
 *
 * @param spreadsheet
 *            Source Spreadsheet
 * @param fileName
 *            Target file name
 * @return File handle to the written file
 * @throws FileNotFoundException
 *             If file was not found
 * @throws IOException
 *             If some other IO error happened
 */
static File write(Spreadsheet spreadsheet, String fileName) throws FileNotFoundException, IOException {
    final Workbook workbook = spreadsheet.getWorkbook();
    if (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")) {
        if (workbook instanceof HSSFWorkbook) {
            fileName += ".xls";
        } else {
            fileName += ".xlsx";
        }
    }
    final File file = new File(fileName);
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file);
        workbook.write(fos);
        fos.close();
        if (workbook instanceof SXSSFWorkbook) {
            ((SXSSFWorkbook) workbook).dispose();
        }
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, e.getMessage(), e);
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
    try {
        Workbook wb = WorkbookFactory.create(file);
        spreadsheet.setInternalWorkbook(wb);
    } catch (InvalidFormatException e) {
        LOGGER.log(Level.WARNING, e.getMessage(), e);
    }
    return file;
}

From source file:com.vaadin.addon.spreadsheet.SpreadsheetFactory.java

License:Open Source License

/**
 * Writes the current Workbook state from the given Spreadsheet to the given
 * output stream. The stream will be closed after writing.
 *
 * @param spreadsheet/*from  w  w  w. j av  a2 s. c  om*/
 *            Source Spreadsheet
 * @param stream
 *            Output stream to write to
 * @throws IOException
 *             If there was an error handling the stream.
 */
static void write(Spreadsheet spreadsheet, OutputStream stream) throws IOException {
    final Workbook workbook = spreadsheet.getWorkbook();
    try {
        workbook.write(stream);
        stream.close();
        stream = null;
        if (workbook instanceof SXSSFWorkbook) {
            ((SXSSFWorkbook) workbook).dispose();
        }
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:com.validation.manager.core.tool.requirement.importer.RequirementImporter.java

License:Apache License

public static File exportTemplate() throws FileNotFoundException, IOException, InvalidFormatException {
    File template = new File("Template.xls");
    template.createNewFile();/*from w  w w .j a  va 2  s  .com*/
    org.apache.poi.ss.usermodel.Workbook wb = new HSSFWorkbook();
    org.apache.poi.ss.usermodel.Sheet sheet = wb.createSheet();
    wb.setSheetName(0, "Requirements");
    int column = 0;
    CellStyle cs = wb.createCellStyle();
    cs.setDataFormat(getBuiltinFormat("text"));
    Font f = wb.createFont();
    f.setFontHeightInPoints((short) 12);
    f.setBold(true);
    f.setColor((short) Font.COLOR_NORMAL);
    cs.setFont(f);
    Row newRow = sheet.createRow(0);
    for (String label : COLUMNS) {
        Cell newCell = newRow.createCell(column);
        newCell.setCellStyle(cs);
        newCell.setCellValue(label);
        column++;
    }

    try (FileOutputStream out = new FileOutputStream(template)) {
        wb.write(out);
        out.close();
    } catch (FileNotFoundException e) {
        LOG.log(Level.SEVERE, null, e);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, null, e);
    }
    return template;
}

From source file:com.validation.manager.core.tool.step.importer.StepImporter.java

License:Apache License

public static File exportTemplate() throws FileNotFoundException, IOException, InvalidFormatException {
    File template = new File("Template.xls");
    template.createNewFile();//from   w w  w.  j  a  va  2  s.com
    org.apache.poi.ss.usermodel.Workbook wb = new HSSFWorkbook();
    org.apache.poi.ss.usermodel.Sheet sheet = wb.createSheet();
    wb.setSheetName(0, "Steps");
    int column = 0;
    CellStyle cs = wb.createCellStyle();
    cs.setDataFormat(getBuiltinFormat("text"));
    Font f = wb.createFont();
    f.setFontHeightInPoints((short) 12);
    f.setBold(true);
    f.setColor((short) Font.COLOR_NORMAL);
    cs.setFont(f);
    Row newRow = sheet.createRow(0);
    for (String label : COLUMNS) {
        Cell newCell = newRow.createCell(column);
        newCell.setCellStyle(cs);
        newCell.setCellValue(label);
        column++;
    }

    try (FileOutputStream out = new FileOutputStream(template)) {
        wb.write(out);
        out.close();
    } catch (FileNotFoundException e) {
        LOG.log(Level.SEVERE, null, e);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, null, e);
    }
    return template;
}

From source file:com.vincestyling.apkinfoextractor.core.export.ExportToExcel.java

License:Apache License

@Override
public void export() throws Exception {
    Workbook wb = new HSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);

    Sheet sheet = wb.createSheet(Constancts.APP_NAME);
    sheet.setHorizontallyCenter(true);/*from ww w .j  a v  a  2 s .  c  om*/
    sheet.setFitToPage(true);

    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(45);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue(
            "  File generated by ApkInfoExtractor (https://github.com/vince-styling/ApkInfoExtractor), Copyright (C) 2014 Vince Styling");
    titleCell.setCellStyle(styles.get("title"));

    Row headerRow = sheet.createRow(1);
    headerRow.setHeightInPoints(40);

    int cellNum = 0;
    String[] fields = solution.getExtractFields().split(",");
    for (String field : fields) {
        if (field.equals(Constancts.ICON))
            continue;
        Cell headerCell = headerRow.createCell(cellNum);
        headerCell.setCellValue(field);
        headerCell.setCellStyle(styles.get("header"));
        sheet.setColumnWidth(cellNum, ApkInfo.getFieldCharacterCount(field) * 256);
        cellNum++;
    }

    int rowNum = 2;
    for (int i = 0; i < solution.getResultCount(); i++) {
        ResultDataProvider provider = solution.getResultList().get(i);
        postProgress(i + 1);

        cellNum = 0;
        Row row = sheet.createRow(rowNum++);
        for (String field : fields) {
            if (field.equals(Constancts.ICON))
                continue;
            Cell cell = row.createCell(cellNum);
            cell.setCellStyle(styles.get("cell"));
            String value = getFieldValue(provider.getApkInfo(), field);
            cell.setCellValue(value);
            cellNum++;
        }
        row.setHeight((short) (5 * 256));
    }

    File outputFile = new File(solution.getWorkingFolder(), solution.generateOutputFileName() + ".xls");
    FileOutputStream out = new FileOutputStream(outputFile);
    wb.write(out);
    out.close();

    callback.onProcessSuccess(outputFile);
}

From source file:com.wabacus.WabacusFacade.java

License:Open Source License

private static void exportReportDataOnPlainExcel(String pageid, ReportRequest rrequest,
        WabacusResponse wresponse) {//ww  w  .  j  av  a2 s .  c  om
    boolean success = true;
    try {
        rrequest.setWResponse(wresponse);
        wresponse.setRRequest(rrequest);
        rrequest.init(pageid);
        if (rrequest.getLstAllReportBeans() == null || rrequest.getLstAllReportBeans().size() == 0) {
            throw new WabacusRuntimeException("?" + pageid
                    + "?plainexcel???");
        }
        Workbook workbook = new HSSFWorkbook();
        AbsReportType reportTypeObjTmp;
        for (ReportBean rbTmp : rrequest.getLstAllReportBeans()) {
            reportTypeObjTmp = (AbsReportType) rrequest.getComponentTypeObj(rbTmp, null, false);
            reportTypeObjTmp.displayOnPlainExcel(workbook);
        }
        BufferedOutputStream bos = null;
        if (rrequest.isExportToLocalFile()) {
            bos = new BufferedOutputStream(new FileOutputStream(new File(rrequest.getDataExportFilepath())));
        } else {
            String title = WabacusAssistant.getInstance().encodeAttachFilename(rrequest.getRequest(),
                    rrequest.getDataExportFilename());
            wresponse.getResponse().setHeader("Content-disposition", "attachment;filename=" + title + ".xls");
            bos = new BufferedOutputStream(wresponse.getResponse().getOutputStream());
        }
        workbook.write(bos);
        bos.close();
        if (rrequest.isExportToLocalFile() && rrequest.isDataexport_localstroagezip()) {
            tarDataFile(rrequest);
        }
    } catch (WabacusRuntimeTerminateException wrwe) {
        if (wresponse.getStatecode() == Consts.STATECODE_FAILED) {
            success = false;
        }
    } catch (Exception wre) {
        wresponse.setStatecode(Consts.STATECODE_FAILED);
        log.error("?" + rrequest.getPagebean().getId() + "", wre);
        success = false;
    } finally {
        rrequest.destroy(success);
    }
    doPostDataExport(rrequest, wresponse);
}

From source file:com.waku.mmdataextract.IMEIMerge.java

License:Open Source License

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("IMEI");
    int colIndex = 0;
    int rowIndex = 0;
    Row row = sheet.createRow(rowIndex++);
    row.createCell(colIndex++).setCellValue("");
    row.createCell(colIndex++).setCellValue("?");
    row.createCell(colIndex++).setCellValue("?");
    row.createCell(colIndex++).setCellValue("IMEI");
    int i = 0;//  www  .j a v  a 2  s .  co  m
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("Brand.xml");
    for (Element brand : (List<Element>) new SAXReader().read(in).selectNodes("/brand/option")) {
        String brandName = brand.getText();
        System.out.println(brandName);
        File file = new File("output/" + brandName + ".csv");
        if (file.exists()) {
            System.out.println("Found file ->" + file.getAbsolutePath());
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String line = null;
            boolean noDataAvailable = true;
            while ((line = br.readLine()) != null) {
                if (line.indexOf(",") != -1) {
                    rowIndex = addRow(line.split(","), sheet, rowIndex);
                    noDataAvailable = false;
                }
            }
            if (noDataAvailable) {
                System.out.println("No data for " + brandName);
                rowIndex = addRow(new String[] { "", brandName, "N/A", "N/A" }, sheet, rowIndex);
            }
            br.close();
        } else {
            System.out.println("No file for " + brandName);
            rowIndex = addRow(new String[] { "", brandName, "N/A", "N/A" }, sheet, rowIndex);
        }
        System.out.println(i++);
    }
    System.out.println(i);
    System.out.println(" ---------------------------------- File saved!");
    wb.write(new FileOutputStream(new File("IMEI.xls")));
}

From source file:com.wantdo.stat.excel.poi_src.AddDimensionedImage.java

License:Apache License

/**
 * The main entry point to the program. It contains code that demonstrates
 * one way to use the program.//from   w  w  w .  j  ava  2s.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(); // OR XSSFWorkbook
        sheet = workbook.createSheet("Picture Test");
        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:com.wantdo.stat.excel.poi_src.AligningCells.java

License:Apache License

public static void main(String[] args) throws IOException {
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();

    Sheet sheet = wb.createSheet();/*from   ww  w.ja  va2s  .co m*/
    Row row = sheet.createRow((short) 2);
    row.setHeightInPoints(30);
    for (int i = 0; i < 8; i++) {
        //column width is set in units of 1/256th of a character width
        sheet.setColumnWidth(i, 256 * 15);
    }

    createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM);
    createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM);
    createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER);
    createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER);
    createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY);
    createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP);
    createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("ss-example-align.xlsx");
    wb.write(fileOut);
    fileOut.close();
}

From source file:com.wantdo.stat.excel.poi_src.ConditionalFormats.java

License:Apache License

public static void main(String[] args) throws IOException {
    Workbook wb;

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else//  ww  w  .j  a va2s .c  om
        wb = new XSSFWorkbook();

    sameCell(wb.createSheet("Same Cell"));
    multiCell(wb.createSheet("MultiCell"));
    errors(wb.createSheet("Errors"));
    hideDupplicates(wb.createSheet("Hide Dups"));
    formatDuplicates(wb.createSheet("Duplicates"));
    inList(wb.createSheet("In List"));
    expiry(wb.createSheet("Expiry"));
    shadeAlt(wb.createSheet("Shade Alt"));
    shadeBands(wb.createSheet("Shade Bands"));

    // Write the output to a file
    String file = "cf-poi.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();

}