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.report.template.LoanCalculator.java

License:Apache License

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

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

    Map<String, CellStyle> styles = createStyles(wb);
    Sheet sheet = wb.createSheet("Loan Calculator");
    sheet.setPrintGridlines(false);
    sheet.setDisplayGridlines(false);

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    sheet.setColumnWidth(0, 3 * 256);
    sheet.setColumnWidth(1, 3 * 256);
    sheet.setColumnWidth(2, 11 * 256);
    sheet.setColumnWidth(3, 14 * 256);
    sheet.setColumnWidth(4, 14 * 256);
    sheet.setColumnWidth(5, 14 * 256);
    sheet.setColumnWidth(6, 14 * 256);

    createNames(wb);

    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(35);
    for (int i = 1; i <= 7; i++) {
        titleRow.createCell(i).setCellStyle(styles.get("title"));
    }
    Cell titleCell = titleRow.getCell(2);
    titleCell.setCellValue("Simple Loan Calculator");
    sheet.addMergedRegion(CellRangeAddress.valueOf("$C$1:$H$1"));

    Row row = sheet.createRow(2);
    Cell cell = row.createCell(4);
    cell.setCellValue("Enter values");
    cell.setCellStyle(styles.get("item_right"));

    row = sheet.createRow(3);
    cell = row.createCell(2);
    cell.setCellValue("Loan amount");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellValue("123123");
    cell.setCellStyle(styles.get("input_$"));
    cell.setAsActiveCell();

    row = sheet.createRow(4);
    cell = row.createCell(2);
    cell.setCellValue("Annual interest rate");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_%"));

    row = sheet.createRow(5);
    cell = row.createCell(2);
    cell.setCellValue("Loan period in years");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_i"));

    row = sheet.createRow(6);
    cell = row.createCell(2);
    cell.setCellValue("Start date of loan");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_d"));

    row = sheet.createRow(8);
    cell = row.createCell(2);
    cell.setCellValue("Monthly payment");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Monthly_Payment,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    row = sheet.createRow(9);
    cell = row.createCell(2);
    cell.setCellValue("Number of payments");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Loan_Years*12,\"\")");
    cell.setCellStyle(styles.get("formula_i"));

    row = sheet.createRow(10);
    cell = row.createCell(2);
    cell.setCellValue("Total interest");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Total_Cost-Loan_Amount,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    row = sheet.createRow(11);
    cell = row.createCell(2);
    cell.setCellValue("Total cost of loan");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Monthly_Payment*Number_of_Payments,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

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

From source file:com.rodrigodev.xgen4j_table_generator.model.table.TableWriter.java

License:Open Source License

public void write(InformationWrapper information, OutputStream output) {
    try {/*from  w ww. ja v  a  2  s.  co  m*/
        Workbook wb = new XSSFWorkbook();
        Table table = new Table(wb.createSheet());

        writeHeaders(information, table.newRow());
        for (ErrorInfoWrapper errorInfo : information.list()) {
            writeContent(errorInfo, table.newRow());
        }

        wb.write(output);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.sany.appbom.action.AppBomController.java

License:Open Source License

public static void sendFile(HttpServletRequest request, HttpServletResponse response, String filename,
        Workbook workbook, long fileSize) throws Exception {
    OutputStream out = null;/*from w  ww  .j av  a2 s  . com*/
    try {
        if (workbook == null)
            return;
        out = response.getOutputStream();

        response.setHeader("Content-Disposition",
                "attachment; filename=" + new String(filename.getBytes(), "ISO-8859-1").replaceAll(" ", "-"));
        response.setHeader("Accept-Ranges", "bytes");
        workbook.write(out);
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.seer.datacruncher.profiler.spring.ExporterController.java

License:Open Source License

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String type = CommonUtil.notNullValue(request.getParameter("exportaction"));
    String columns = CommonUtil.notNullValue(request.getParameter("exportcolumns"));
    String data = CommonUtil.notNullValue(request.getParameter("exportdata"));

    if (type.equals("csv")) {
        PrintWriter out = response.getWriter();
        response.setContentType("application/csv");
        response.setHeader("content-disposition", "attachment;filename=analysis_data.csv"); // set the file
        // name to
        // whatever
        // required..
        out.println(columns.replace("&&&&&", ","));
        for (String strData : data.split("@@@@@")) {
            out.println(strData.replace("&&&&&", ","));
        }/*ww  w . j  a va2s .  co  m*/
        out.flush();
        out.close();
    } else if (type.equals("xml")) {
        PrintWriter out = response.getWriter();
        response.setContentType("text/xml");
        response.setHeader("content-disposition", "attachment;filename=analysis_data.xml"); // set the file
        // name to
        // whatever
        // required..
        try {
            StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
            xml.append("<table><header>");
            String colArr[] = columns.split("&&&&&");
            for (String col : colArr) {
                xml.append("<columnName>" + col + "</columnName>");
            }
            xml.append("</header>");

            for (String strData : data.split("@@@@@")) {
                xml.append("<row>");
                int ind = 0;
                for (String val : strData.split("&&&&&")) {
                    xml.append("<" + colArr[ind] + ">" + val + "</" + colArr[ind] + "/>");
                    ind++;
                }
                xml.append("</row>");
            }
            xml.append("</table>");
            out.print(xml.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        out.flush();
        out.close();
    } else if (type.equals("excel")) {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=analysis_data.xls");
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("new sheet");
        String colArr[] = columns.split("&&&&&");
        short ind = 0;
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style.setFont(font);
        Row row = sheet.createRow(0);
        for (String col : colArr) {
            Cell cell = row.createCell(ind);
            cell.setCellValue(col);
            cell.setCellStyle(style);
            ind++;
        }
        ind = 1;
        for (String strData : data.split("@@@@@")) {
            Row valRow = sheet.createRow(ind);
            short cellInd = 0;
            for (String val : strData.split("&&&&&")) {
                valRow.createCell(cellInd).setCellValue(val);
                cellInd++;
            }
            ind++;
        }

        // Write the output to a file
        OutputStream resOout = response.getOutputStream();
        wb.write(resOout);
        resOout.close();

    }

    return null;
}

From source file:com.setu.hsapiassistance.service.ApiAssistanceService.java

private void createFile(Workbook wb) throws IOException {
    try (FileOutputStream fileOut = new FileOutputStream("Timeline.xls")) {
        wb.write(fileOut);
    }//from  ww w.  j a  v a 2  s .  co m
}

From source file:com.shiyq.poi.HSSFTest.java

public static boolean createExcel(String excelName) {
    boolean created = false;
    Workbook wb = new HSSFWorkbook();
    Font font = wb.createFont();/*from ww  w  .  ja  v  a 2  s  . c o m*/
    font.setBold(true);
    CellStyle headStyle = wb.createCellStyle();
    headStyle.setFont(font);

    Sheet sheet = wb.createSheet("20165???");
    String[] head = { "??", "?", "??", "???", "????",
            "????", "?", "??", "", "",
            "??" };
    String[] code = { "card_no", "card_type", "spread_time", "spread_emp_no", "spread_emp_name", "owner_name",
            "plate", "blance", "start_time", "end_time", "month_money" };

    List<Map<String, Object>> list = setList();
    setSheet(sheet, list, head, headStyle, code);
    //
    int startRow = 4;
    int endRow = 8;
    int startColumn = head.length + 4;
    int endColumn = head.length + 8;

    String describe = "1?" + (new Date().toString()) + "\n";
    describe += "2.\n";
    describe += "3.?2016-4-42016-5-4";
    CellStyle descStyle = wb.createCellStyle();
    descStyle.setAlignment(CellStyle.ALIGN_LEFT);
    descStyle.setVerticalAlignment(CellStyle.VERTICAL_TOP);
    setSheet(sheet, startRow, endRow, startColumn, endColumn, describe, descStyle);

    Sheet sheet1 = wb.createSheet("20166???");
    setSheet(sheet1, list, head, headStyle, code);
    setSheet(sheet1, startRow, endRow, startColumn, endColumn, describe, descStyle);
    try {
        try (FileOutputStream fileOut = new FileOutputStream(excelName)) {
            wb.write(fileOut);
            created = true;
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(HSSFTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(HSSFTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return created;
}

From source file:com.siberhus.tdfl.DflBaseTest.java

License:Apache License

@Before
public void createXLSFile() throws Exception {
    if (new File(XLS_FILE_IN_NAME).exists()) {
        return;//  w  w  w.jav a2 s .c  o  m
    }
    Workbook workbook = new HSSFWorkbook();
    Sheet sheet = workbook.createSheet("Untitled");
    String dataArray[][] = getTestData();
    for (int i = 0; i < dataArray.length; i++) {
        String data[] = dataArray[i];
        Row row = sheet.createRow(i);
        for (int j = 0; j < data.length; j++) {
            row.createCell(j).setCellValue(data[j]);
        }
    }
    OutputStream out = new FileOutputStream(XLS_FILE_IN_NAME);
    workbook.write(out);
    IOUtils.closeQuietly(out);
}

From source file:com.siemens.sw360.exporter.ExcelExporter.java

License:Open Source License

public InputStream makeExcelExport(List<T> documents) throws IOException {
    final Workbook workbook = new XSSFWorkbook();

    Sheet sheet = workbook.createSheet("Component Data");

    /** Adding styles to cells */
    CellStyle cellStyte = createCellStyte(workbook);
    CellStyle headerStyle = createHeaderStyle(workbook);

    /** Create header row */
    Row headerRow = sheet.createRow(0);//from  w  w w  . j a v  a2s  . co  m
    List<String> headerNames = helper.getHeaders();
    fillRow(headerRow, headerNames, headerStyle);

    /** Create data rows */
    fillValues(sheet, documents, cellStyte);

    /** Resize the columns */
    for (int iColumns = 0; iColumns < nColumns; iColumns++) {
        sheet.autoSizeColumn(iColumns);
    }

    /** Copy the streams */
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    workbook.write(out);

    return new ByteArrayInputStream(out.toByteArray());
}

From source file:com.simopuve.helper.ExcelWrapperHelper.java

public static void WritePDVToExcell(PDVSurvey survey) {
    String pointOfSaleName = survey.getHeader().getPointOfSaleName().replace(" ", "");
    String folderName = new StringBuilder()
            .append(new DecimalFormat("00").format(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)))
            .append("-").append(new DecimalFormat("00").format(Calendar.getInstance().get(Calendar.MONTH) + 1))
            .append("-").append(Calendar.getInstance().get(Calendar.YEAR)).toString();
    String filePath = new StringBuilder(System.getProperty("jboss.server.data.dir")).append("/PDV/")
            .append(folderName).append("/").append(survey.getHeader().isMall() ? "Mall/" : "Oficina/")
            .toString();//from  www . j a  v  a 2 s . co  m
    String fileName = new StringBuilder(pointOfSaleName).append(".xls").toString();
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("pseudo-platilla.xlsx");
    try {
        Workbook book1 = new XSSFWorkbook(is);
        is.close();
        Sheet sheet = book1.getSheetAt(0);
        ExcelFiller.fillHeader(survey.getHeader(), sheet);
        ExcelFiller.fillRows(sheet, survey.getRows());
        File directory = new File(filePath);
        directory.mkdirs();
        FileOutputStream fileOut = new FileOutputStream(filePath + fileName);
        book1.write(fileOut);
        fileOut.close();
    } catch (IOException ex) {
        Logger.getLogger(ExcelWrapperHelper.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.simopuve.helper.POIHelper.java

public static void writeWorkbookInPath(Workbook wb, String path) {
    try {/*  w ww .  j a v  a2 s. co m*/
        FileOutputStream out = new FileOutputStream(path);
        wb.write(out);
        out.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(POIHelper.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(POIHelper.class.getName()).log(Level.SEVERE, null, ex);
    }
}