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

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

Introduction

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

Prototype

public XSSFWorkbook() 

Source Link

Document

Create a new SpreadsheetML workbook.

Usage

From source file:com.jornada.server.service.GWTServiceNotaImpl.java

License:Open Source License

public String getExcelBoletimAnual(ArrayList<TableMultipleBoletimAnual> listTableMBD) {

    XSSFWorkbook wb = new XSSFWorkbook();
    for (int i = 0; i < listTableMBD.size(); i++) {
        TableMultipleBoletimAnual tableMBD = listTableMBD.get(i);
        String strTab = Integer.toString(i + 1) + ") ";
        strTab += tableMBD.getNomeCurso().substring(0, 3);
        XSSFSheet sheet = wb.createSheet(strTab);
        NotaServer.getExcelBoletimAnual(wb, sheet, tableMBD.getIdCurso());
    }//from  w w w  . j  a  v  a 2 s.  c o m
    return ExcelFramework.getExcelAddress(wb, "GerarExcelBoletimAnual_");
}

From source file:com.jornada.server.service.GWTServiceNotaImpl.java

License:Open Source License

public String getExcelBoletimDisciplina(int idCurso, int idPeriodo, int idDisciplina) {
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet("Boletim Disciplina");
    NotaServer.gerarExcelBoletimDisciplina(wb, sheet, idCurso, idPeriodo, idDisciplina);
    return ExcelFramework.getExcelAddress(wb, "GerarExcelBoletimDisciplina_");
}

From source file:com.jornada.server.service.GWTServiceNotaImpl.java

License:Open Source License

public String getExcelBoletimDisciplina(ArrayList<TableMultipleBoletimDisciplina> listTableMBD) {
    XSSFWorkbook wb = new XSSFWorkbook();
    for (int i = 0; i < listTableMBD.size(); i++) {
        TableMultipleBoletimDisciplina tableMBD = listTableMBD.get(i);
        String strTab = Integer.toString(i + 1) + ") ";
        strTab += tableMBD.getNomeCurso().substring(0, 3) + "-";
        strTab += tableMBD.getNomePeriodo().substring(0, 3) + "-";
        strTab += tableMBD.getNomeDisciplina().substring(0, 3);
        XSSFSheet sheet = wb.createSheet(strTab);
        NotaServer.gerarExcelBoletimDisciplina(wb, sheet, tableMBD.getIdCurso(), tableMBD.getIdPeriodo(),
                tableMBD.getIdDisciplina());
    }/*from   w  w  w  . j ava  2 s.  com*/

    return ExcelFramework.getExcelAddress(wb, "GerarExcelBoletimDisciplina_");
}

From source file:com.kafeidev.test.BusinessPlan.java

License:Apache License

@Test
public static void main(String[] args) throws Exception {
    Workbook wb;/*from w ww  .  ja v a2  s  .co m*/

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else
        wb = new XSSFWorkbook();

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

    Sheet sheet = wb.createSheet("Business Plan");

    //turn off gridlines
    sheet.setDisplayGridlines(false);
    sheet.setPrintGridlines(false);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);

    //the following three statements are required only for HSSF
    sheet.setAutobreaks(true);
    printSetup.setFitHeight((short) 1);
    printSetup.setFitWidth((short) 1);

    //the header row: centered text in 48pt font
    Row headerRow = sheet.createRow(0);
    headerRow.setHeightInPoints(12.75f);
    for (int i = 0; i < titles.length; i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellValue(titles[i]);
        cell.setCellStyle(styles.get("header"));
    }
    //columns for 11 weeks starting from 9-Nov
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    //        {
    //           String inputDate = "2010-Nov-04 01:32:27";
    //           Date date = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss", new Locale("en,EN")).parse(inputDate);
    //            String str= new SimpleDateFormat("dd.MMM.yyyy HH:mm:ss").format(date);
    //            System.out.println("data:"+str);
    //            
    //        }
    calendar.setTime(fmt.parse("19-Nov"));
    calendar.set(Calendar.YEAR, year);
    for (int i = 0; i < 11; i++) {
        Cell cell = headerRow.createCell(titles.length + i);
        cell.setCellValue(calendar);
        cell.setCellStyle(styles.get("header_date"));
        calendar.roll(Calendar.WEEK_OF_YEAR, true);
    }
    //freeze the first row
    sheet.createFreezePane(0, 1);

    Row row;
    Cell cell;
    int rownum = 1;
    for (int i = 0; i < data.length; i++, rownum++) {
        row = sheet.createRow(rownum);
        if (data[i] == null)
            continue;

        for (int j = 0; j < data[i].length; j++) {
            cell = row.createCell(j);
            String styleName;
            boolean isHeader = i == 0 || data[i - 1] == null;
            switch (j) {
            case 0:
                if (isHeader) {
                    styleName = "cell_b";
                    cell.setCellValue(Double.parseDouble(data[i][j]));
                } else {
                    styleName = "cell_normal";
                    cell.setCellValue(data[i][j]);
                }
                break;
            case 1:
                if (isHeader) {
                    styleName = i == 0 ? "cell_h" : "cell_bb";
                } else {
                    styleName = "cell_indented";
                }
                cell.setCellValue(data[i][j]);
                break;
            case 2:
                styleName = isHeader ? "cell_b" : "cell_normal";
                cell.setCellValue(data[i][j]);
                break;
            case 3:
                styleName = isHeader ? "cell_b_centered" : "cell_normal_centered";
                cell.setCellValue(Integer.parseInt(data[i][j]));
                break;
            case 4: {
                calendar.setTime(fmt.parse(data[i][j]));
                calendar.set(Calendar.YEAR, year);
                cell.setCellValue(calendar);
                styleName = isHeader ? "cell_b_date" : "cell_normal_date";
                break;
            }
            case 5: {
                int r = rownum + 1;
                String fmla = "IF(AND(D" + r + ",E" + r + "),E" + r + "+D" + r + ",\"\")";
                cell.setCellFormula(fmla);
                styleName = isHeader ? "cell_bg" : "cell_g";
                break;
            }
            default:
                styleName = data[i][j] != null ? "cell_blue" : "cell_normal";
            }

            cell.setCellStyle(styles.get(styleName));
        }
    }

    //group rows for each phase, row numbers are 0-based
    sheet.groupRow(4, 6);
    sheet.groupRow(9, 13);
    sheet.groupRow(16, 18);

    //set column widths, the width is measured in units of 1/256th of a character width
    sheet.setColumnWidth(0, 256 * 6);
    sheet.setColumnWidth(1, 256 * 33);
    sheet.setColumnWidth(2, 256 * 20);
    sheet.setZoom(3, 4);

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

From source file:com.khartec.waltz.web.endpoints.extracts.BaseDataExtractor.java

License:Open Source License

private Object writeAsExcel(String suggestedFilenameStem, Select<?> qry, Response response) throws IOException {
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet(sanitizeSheetName(suggestedFilenameStem));

    writeExcelHeader(qry, sheet);/*from www . j av  a 2 s .com*/
    writeExcelBody(qry, sheet);

    sheet.setAutoFilter(new CellRangeAddress(0, 0, 0, qry.fields().length));
    sheet.createFreezePane(0, 1);

    byte[] bytes = convertExcelToByteArray(workbook);

    HttpServletResponse httpResponse = response.raw();

    httpResponse.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    httpResponse.setHeader("Content-Disposition", "attachment; filename=" + suggestedFilenameStem + ".xlsx");
    httpResponse.setHeader("Content-Transfer-Encoding", "7bit");

    httpResponse.setContentLength(bytes.length);
    httpResponse.getOutputStream().write(bytes);
    httpResponse.getOutputStream().flush();
    httpResponse.getOutputStream().close();

    return httpResponse;
}

From source file:com.kybelksties.excel.ExcelWorkbookTableModel.java

License:Open Source License

/**
 * Default construct.
 */
public ExcelWorkbookTableModel() {
    setWorkbook(new XSSFWorkbook());
    addSheet();
}

From source file:com.l3.info.magenda.emplois_du_temps.Workbook.java

public Workbook() {
    workbook = new XSSFWorkbook();
    initialiserPalettedestyle(workbook);
}

From source file:com.liferay.events.global.mobile.portlet.PollsPortlet.java

License:Open Source License

@Override
public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {
    // do search and return result
    String cmd = ParamUtil.getString(request, "cmd");
    long questionId = ParamUtil.getLong(request, "questionId");

    EventPollQuestion question;//from   ww  w.java2 s.c o  m
    List<EventPollAnswer> answers;
    try {
        question = EventPollQuestionLocalServiceUtil.getEventPollQuestion(questionId);
        answers = EventPollAnswerLocalServiceUtil.getAllAnswerObjs(questionId);
    } catch (SystemException e) {
        throw new PortletException("Cannot get answers for questionId " + questionId);
    } catch (PortalException e) {
        throw new PortletException("Cannot get question or answers for questionId " + questionId);
    }

    if (Validator.equals(cmd, "exportAnswersCSV")) {

        File f = FileUtil.createTempFile();

        CSVWriter writer = new CSVWriter(new FileWriter(f), ',');

        // find out all headers
        List<String> headers = new ArrayList<String>();
        headers.add("ID");
        headers.add("RAW ANSWER");

        Set<String> payloadHeaders = new HashSet<String>();

        for (EventPollAnswer answer : answers) {
            JSONObject payloadObj = null;

            try {
                payloadObj = JSONFactoryUtil.createJSONObject(answer.getPayload());
                if (Validator.isNull(payloadObj)) {
                    continue;
                }
            } catch (JSONException e) {
                throw new PortletException("cannot read payload: " + answer.getPayload());
            }
            Iterator<String> keyIt = payloadObj.keys();

            while (keyIt.hasNext()) {
                String key = keyIt.next();
                payloadHeaders.add(key);
            }
        }

        headers.addAll(payloadHeaders);

        Map<String, Integer> headerCols = new HashMap<String, Integer>();
        for (int i = 0; i < headers.size(); i++) {
            headerCols.put(headers.get(i), i);
        }

        // now print them
        writer.writeNext(headers.toArray(new String[] {}));

        for (EventPollAnswer answer : answers) {
            List<String> vals = new ArrayList<String>();

            JSONObject payloadObj = null;

            try {
                payloadObj = JSONFactoryUtil.createJSONObject(answer.getPayload());
                if (Validator.isNull(payloadObj)) {
                    continue;
                }
            } catch (JSONException e) {
                throw new PortletException("cannot read payload: " + answer.getPayload());
            }

            for (String headerCol : headers) {
                String val;
                if (headerCol.equals("ID")) {
                    val = String.valueOf(answer.getAnswerId());
                } else if (headerCol.equals("RAW ANSWER")) {
                    val = String.valueOf(answer.getAnswer());
                } else {
                    val = payloadObj.getString(headerCol);
                }

                if (Validator.isNull(val)) {
                    val = "";
                }
                vals.add(val);
            }

            writer.writeNext(vals.toArray(new String[] {}));
        }
        writer.flush();
        writer.close();
        PortletResponseUtil.sendFile(request, response,
                question.getShortTitle().replaceAll("[^0-9A-Za-z]", "-") + ".csv", new FileInputStream(f));

    } else if (Validator.equals(cmd, "exportAnswersXLSX")) {

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Poll Answers");

        Row headerRow = sheet.createRow(0);
        Cell headerCell = headerRow.createCell(0);
        headerCell.setCellValue("ID");

        headerCell = headerRow.createCell(1);
        headerCell.setCellValue("Raw Answer");

        HashMap<String, Integer> rowMap = new HashMap<String, Integer>();

        int currentRow = 1;
        int nextHeaderCol = 2;
        for (EventPollAnswer answer : answers) {
            Row row = sheet.createRow(currentRow);
            currentRow++;
            JSONObject payloadObj = null;
            long answerId = answer.getAnswerId();
            Cell idCell = row.createCell(0);
            idCell.setCellValue(String.valueOf(answerId));

            try {
                payloadObj = JSONFactoryUtil.createJSONObject(answer.getPayload());
                if (Validator.isNull(payloadObj)) {
                    continue;
                }
            } catch (JSONException e) {
                throw new PortletException("cannot read payload: " + answer.getPayload());
            }

            Cell answerCell = row.createCell(1);
            answerCell.setCellValue(String.valueOf(answer.getAnswer()));

            Iterator<String> keyIt = payloadObj.keys();

            while (keyIt.hasNext()) {
                String key = keyIt.next();
                Integer headerCol = rowMap.get(key);
                if (Validator.isNull(headerCol)) {
                    rowMap.put(key, nextHeaderCol);
                    Cell nextHeaderCell = headerRow.createCell(nextHeaderCol);
                    nextHeaderCell.setCellValue(key.toUpperCase());
                    headerCol = nextHeaderCol;
                    nextHeaderCol++;
                }
                Cell cell = row.createCell(headerCol);
                cell.setCellValue(payloadObj.getString(key));
            }
        }

        File f = FileUtil.createTempFile();
        FileOutputStream fos = new FileOutputStream(f);
        workbook.write(fos);
        fos.flush();
        fos.close();
        PortletResponseUtil.sendFile(request, response,
                question.getShortTitle().replaceAll("[^0-9A-Za-z]", "-") + ".xlsx", new FileInputStream(f));

    }
}

From source file:com.linus.excel.poi.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.  j  ava 2 s .  c o  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("excel/ss-example-align.xlsx");
    wb.write(fileOut);
    fileOut.close();
    wb.close();
}

From source file:com.linus.excel.poi.MergingCells.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
    Sheet sheet = wb.createSheet("new sheet");

    Row row = sheet.createRow((short) 1);
    Cell cell = row.createCell((short) 1);
    cell.setCellValue(new XSSFRichTextString("This is a test of merging"));

    sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("excel/merging_cells.xlsx");
    wb.write(fileOut);/*from  www . j a  va  2  s  . c o m*/
    fileOut.close();
}