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

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

Introduction

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

Prototype

CreationHelper getCreationHelper();

Source Link

Document

Returns an object that handles instantiating concrete classes of the various instances one needs for HSSF and XSSF.

Usage

From source file:com.alvexcore.repo.documents.generation.ExportReportToXlsx.java

License:Open Source License

protected Workbook createXlsx(JSONArray rows, String XLS_SHEET_NAME) {

    Workbook wb = new XSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet(XLS_SHEET_NAME);

    for (int k = 0; k < rows.size(); k++) {
        Row row = sheet.createRow((short) k);
        JSONArray cells = (JSONArray) rows.get(k);
        row.createCell(0).setCellValue(createHelper.createRichTextString((String) cells.get(0)));
        for (int c = 1; c < cells.size(); c++)
            row.createCell(c).setCellValue((String) cells.get(c));
    }//  w  w w  .  jav a 2  s .  co  m

    return wb;
}

From source file:com.asakusafw.testdata.generator.excel.WorkbookInfo.java

License:Apache License

/**
 * Creates a new instance.//from   w ww .j av  a 2  s  .  c o m
 * @param workbook target workbook
 * @throws IllegalArgumentException if some parameters were {@code null}
 */
public WorkbookInfo(Workbook workbook) {
    if (workbook == null) {
        throw new IllegalArgumentException("workbook must not be null"); //$NON-NLS-1$
    }
    this.workbook = workbook;
    this.version = WorkbookGenerator.getSpreadsheetVersion(workbook);

    Font font = workbook.createFont();
    // font.setFontName("...");

    commonStyle = workbook.createCellStyle();
    commonStyle.setFont(font);
    commonStyle.setBorderTop(CellStyle.BORDER_THIN);
    commonStyle.setBorderBottom(CellStyle.BORDER_THIN);
    commonStyle.setBorderLeft(CellStyle.BORDER_THIN);
    commonStyle.setBorderRight(CellStyle.BORDER_THIN);

    titleStyle = workbook.createCellStyle();
    titleStyle.cloneStyleFrom(commonStyle);
    titleStyle.setLocked(true);
    titleStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    titleStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
    titleStyle.setAlignment(CellStyle.ALIGN_CENTER);

    lockedStyle = workbook.createCellStyle();
    lockedStyle.cloneStyleFrom(commonStyle);
    lockedStyle.setLocked(true);
    lockedStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    lockedStyle.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
    lockedStyle.setAlignment(CellStyle.ALIGN_CENTER);

    optionsStyle = workbook.createCellStyle();
    optionsStyle.cloneStyleFrom(commonStyle);
    optionsStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    optionsStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());

    CreationHelper helper = workbook.getCreationHelper();
    DataFormat df = helper.createDataFormat();

    dataStyle = workbook.createCellStyle();
    dataStyle.cloneStyleFrom(commonStyle);

    dateDataStyle = workbook.createCellStyle();
    dateDataStyle.cloneStyleFrom(commonStyle);
    dateDataStyle.setDataFormat(df.getFormat("yyyy-mm-dd")); //$NON-NLS-1$

    timeDataStyle = workbook.createCellStyle();
    timeDataStyle.cloneStyleFrom(commonStyle);
    timeDataStyle.setDataFormat(df.getFormat("hh:mm:ss")); //$NON-NLS-1$

    datetimeDataStyle = workbook.createCellStyle();
    datetimeDataStyle.cloneStyleFrom(commonStyle);
    datetimeDataStyle.setDataFormat(df.getFormat("yyyy-mm-dd hh:mm:ss")); //$NON-NLS-1$
}

From source file:com.asakusafw.testdriver.excel.ExcelSheetDataModelSource.java

License:Apache License

private void evaluateInCell(Cell cell) throws IOException {
    try {/*from w w w  .  jav  a2 s  . c o m*/
        Workbook workbook = cell.getSheet().getWorkbook();
        FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
        formulaEvaluator.evaluateInCell(cell);
    } catch (RuntimeException e) {
        throw new IOException(MessageFormat.format(
                Messages.getString("ExcelSheetDataModelSource.errorFailedToResolveFormulaCell"), //$NON-NLS-1$
                id, cell.getRowIndex() + 1, cell.getColumnIndex() + 1), e);
    }
}

From source file:com.asakusafw.testdriver.excel.WorkbookInfo.java

License:Apache License

/**
 * Creates a new instance./*from   w w w .j  a va 2  s. c  o  m*/
 * @param workbook target workbook
 * @throws IllegalArgumentException if some parameters were {@code null}
 */
public WorkbookInfo(Workbook workbook) {
    if (workbook == null) {
        throw new IllegalArgumentException("workbook must not be null"); //$NON-NLS-1$
    }
    this.workbook = workbook;

    Font font = workbook.createFont();

    commonStyle = workbook.createCellStyle();
    commonStyle.setFont(font);
    commonStyle.setBorderTop(CellStyle.BORDER_THIN);
    commonStyle.setBorderBottom(CellStyle.BORDER_THIN);
    commonStyle.setBorderLeft(CellStyle.BORDER_THIN);
    commonStyle.setBorderRight(CellStyle.BORDER_THIN);

    titleStyle = workbook.createCellStyle();
    titleStyle.cloneStyleFrom(commonStyle);
    titleStyle.setLocked(true);
    titleStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    titleStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
    titleStyle.setAlignment(CellStyle.ALIGN_CENTER);

    CreationHelper helper = workbook.getCreationHelper();
    DataFormat df = helper.createDataFormat();

    dataStyle = workbook.createCellStyle();
    dataStyle.cloneStyleFrom(commonStyle);

    dateDataStyle = workbook.createCellStyle();
    dateDataStyle.cloneStyleFrom(commonStyle);
    dateDataStyle.setDataFormat(df.getFormat("yyyy-mm-dd")); //$NON-NLS-1$

    timeDataStyle = workbook.createCellStyle();
    timeDataStyle.cloneStyleFrom(commonStyle);
    timeDataStyle.setDataFormat(df.getFormat("hh:mm:ss")); //$NON-NLS-1$

    datetimeDataStyle = workbook.createCellStyle();
    datetimeDataStyle.cloneStyleFrom(commonStyle);
    datetimeDataStyle.setDataFormat(df.getFormat("yyyy-mm-dd hh:mm:ss")); //$NON-NLS-1$
}

From source file:com.automaster.autoview.server.servlet.ExcelServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /*response.setContentType("application/vnd.ms-excel");
     response.setHeader("Content-Disposition", "attachment; filename=filename.xls");
     HSSFWorkbook workbook = new HSSFWorkbook();
     // .../* w w w  . j av  a 2 s  .c  o  m*/
     // Now populate workbook the usual way.
     // ...
     OutputStream arqSaida = response.getOutputStream();
     workbook.write(arqSaida); // Write workbook to response.
     arqSaida.flush();
     arqSaida.close();*/
    //getServletContext().getRealPath("/")
    String tempoDecorrido = " 0";
    String url = getServletContext().getRealPath("/");
    String placa = request.getParameter("placa");
    //TimeZone timeZoneMundial = TimeZone.getTimeZone(ZoneId.ofOffset("UTC", ZoneOffset.UTC));
    Timestamp dataInicio = new Timestamp(Long.parseLong(request.getParameter("dataInicio")));
    Timestamp dataFim = new Timestamp(Long.parseLong(request.getParameter("dataFim")));
    //String timeZoneInterface = request.getParameter("timeZone");
    /*String timeZone = "Z";
    if(timeZoneInterface.equalsIgnoreCase("0")){
    timeZone = "Z";
    } else {
    timeZone = String.valueOf((-1) * (Integer.parseInt(timeZoneInterface) / 60));
    }  */
    TimeZone timeZonePadrao = TimeZone.getTimeZone(ZoneId.of("-3"));
    System.out.println("Time zone Cliente : " + timeZonePadrao);
    //System.out.println("timeZoneInterface: "+timeZoneInterface);
    //System.out.println("timeZone: "+timeZone);
    //String ign = request.getParameter("ign");
    ZzzPosPlacaVeiculoDAO zzzPosPlacaVeiculoDAO = new ZzzPosPlacaVeiculoDAO();
    ArrayList<TreeMap<String, String>> posicoes = zzzPosPlacaVeiculoDAO.buscarPosicoesPorIntervaloData(placa,
            dataInicio, dataFim);

    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setHeader("Content-Disposition", "attachment; filename=Historico-" + placa + ".xlsx");

    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("Histrico - " + placa);
    int pictureIdx;
    try ( //add picture data to this workbook.
            InputStream is = new FileInputStream(url + "/imagens/logo.jpg")) {
        byte[] bytes = IOUtils.toByteArray(is);
        pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
    }

    CreationHelper helper = wb.getCreationHelper();

    // Create the drawing patriarch.  This is the top level container for all shapes. 
    Drawing drawing = sheet.createDrawingPatriarch();

    //add a picture shape
    ClientAnchor anchor = helper.createClientAnchor();
    //set top-left corner of the picture,
    //subsequent call of Picture#resize() will operate relative to it
    anchor.setCol1(1);
    anchor.setRow1(0);
    Picture pict = drawing.createPicture(anchor, pictureIdx);
    //auto-size picture relative to its top-left corner
    pict.resize(3, 3);
    //pict.resize();
    //sheet.setColumnWidth(0, 200);

    Font fonte = wb.createFont();
    fonte.setFontHeightInPoints((short) 24);
    fonte.setFontName("Arial");
    fonte.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    fonte.setItalic(true);
    CellStyle estiloTitulo = wb.createCellStyle();
    estiloTitulo.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    estiloTitulo.setFont(fonte);

    Font fonteCabecalho = wb.createFont();
    fonteCabecalho.setFontHeightInPoints((short) 14);
    fonteCabecalho.setFontName("Arial");
    fonteCabecalho.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    //fonteCabecalho.setItalic(true);
    CellStyle estiloCabecalho = wb.createCellStyle();
    estiloCabecalho.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    estiloCabecalho.setFont(fonteCabecalho);

    Font fonteTituloTabela = wb.createFont();
    //fonteTituloTabela.setFontHeightInPoints((short) 14);
    fonteTituloTabela.setFontName("Arial");
    fonteTituloTabela.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

    CellStyle estilo = wb.createCellStyle();
    estilo.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    estilo.setFont(fonteTituloTabela);

    CellStyle estiloCorpo = wb.createCellStyle();
    estiloCorpo.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    //estiloCorpo.setFillBackgroundColor(HSSFColor.WHITE.index);
    //estiloCorpo.setFont(fonteTituloTabela);

    XSSFRow linha6 = (XSSFRow) sheet.createRow(6);
    XSSFCell cell046 = linha6.createCell(3);
    cell046.setCellValue("Relatrio de Posies");
    cell046.setCellStyle(estiloTitulo);
    //sheet.addMergedRegion(new CellRangeAddress(6, 6, 0, 3));

    XSSFRow linha7 = (XSSFRow) sheet.createRow(7);
    XSSFCell cell047 = linha7.createCell(3);
    cell047.setCellValue("Veculo : " + placa);
    cell047.setCellStyle(estiloCabecalho);
    //sheet.addMergedRegion(new CellRangeAddress(7, 7, 0, 3));

    XSSFRow linha8 = (XSSFRow) sheet.createRow(8);
    XSSFCell cell038 = linha8.createCell(3);
    //TimeZone.setDefault(timeZoneMundial);
    //Date dataHoraInicio0 = new Date(Long.parseLong(request.getParameter("dataInicio")));
    //TimeZone.setDefault(timeZoneCliente);
    //Date dataHoraInicio = new Date(dataHoraInicio0.getTime());
    SimpleDateFormat dataFormatadaCabecalho = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    dataFormatadaCabecalho.setTimeZone(timeZonePadrao);
    cell038.setCellValue("Perodo: De: " + dataFormatadaCabecalho.format(dataInicio) + " at: "
            + dataFormatadaCabecalho.format(dataFim));
    cell038.setCellStyle(estiloCabecalho);
    //sheet.addMergedRegion(new CellRangeAddress(8, 8, 0, 3));

    sheet.setColumnWidth(0, 5000);
    sheet.setColumnWidth(1, 3000);
    sheet.setColumnWidth(2, 3500);
    //sheet.setColumnWidth(3, 4000);
    sheet.setColumnWidth(3, 30000);
    //sheet.setColumnWidth(4, 4000);
    //sheet.setColumnWidth(4, 30000);
    sheet.setColumnWidth(5, 3000);
    sheet.setColumnWidth(6, 3000);
    sheet.setColumnWidth(7, 3000);
    sheet.setColumnWidth(8, 3000);
    sheet.setColumnWidth(9, 3000);
    //sheet.setColumnWidth(10, 20000);        
    sheet.setColumnWidth(11, 3000);
    XSSFRow linha9 = (XSSFRow) sheet.createRow(10);
    XSSFCell cell0 = linha9.createCell(0);
    cell0.setCellValue("Data e hora");
    cell0.setCellStyle(estilo);
    XSSFCell cell1 = linha9.createCell(1);
    cell1.setCellValue("Velocidade");
    cell1.setCellStyle(estilo);
    XSSFCell cell2 = linha9.createCell(2);
    cell2.setCellValue("Ignio");
    cell2.setCellStyle(estilo);
    //XSSFCell cell3 = linha9.createCell(3);
    //cell3.setCellValue("Latitude");
    //cell3.setCellStyle(estilo);
    //XSSFCell cell4 = linha9.createCell(4);
    //cell4.setCellValue("Longitude");
    //cell4.setCellStyle(estilo);
    //XSSFCell cell5 = linha9.createCell(5);
    //cell5.setCellValue("Satlite");
    //cell5.setCellStyle(estilo);
    //XSSFCell cell6 = linha9.createCell(6);
    //cell6.setCellValue("GPS");
    //cell6.setCellStyle(estilo);
    //XSSFCell cell7 = linha9.createCell(7);
    //cell7.setCellValue("Entrada");
    //cell7.setCellStyle(estilo);
    //XSSFCell cell8 = linha9.createCell(8);
    //cell8.setCellValue("Sada");
    //cell8.setCellStyle(estilo);
    //XSSFCell cell9 = linha9.createCell(9);
    //cell9.setCellValue("Evento");
    //cell9.setCellStyle(estilo);
    XSSFCell cell10 = linha9.createCell(3);
    cell10.setCellValue("Endereo");
    cell10.setCellStyle(estilo);
    //sheet.addMergedRegion(new CellRangeAddress(11, 11, 4, 8));
    //XSSFCell cell11 = linha9.createCell(11);
    //cell11.setCellValue("Direo");
    //cell11.setCellStyle(estilo);
    int linha = 0;
    int j = 11;
    double latAnt = 0;
    double lonAnt = 0;
    double latAtual = 0;
    double lonAtual = 0;
    double distancia = 0;
    double distanciaTotal = 0;
    for (int i = 0; i < posicoes.size(); i++) {
        XSSFRow row = (XSSFRow) sheet.createRow(j);
        if (i == 0) {
            distancia = 0;
            //System.out.println("linha 00 - EXCEL");
        } else {
            //System.out.println("linha 01 - EXCEL");
            latAnt = Double.parseDouble(posicoes.get(i - 1).get("lat"));
            lonAnt = Double.parseDouble(posicoes.get(i - 1).get("lon"));
            latAtual = Double.parseDouble(posicoes.get(i).get("lat"));
            lonAtual = Double.parseDouble(posicoes.get(i).get("lon"));
            //System.out.println("linha 02 - PDF");
            if (latAnt == latAtual && lonAnt == lonAtual) {
                distancia = 0;
            } else {
                distancia = caculaDistanciaEntreDoisPontos(latAnt, lonAnt, latAtual, lonAtual);
                //System.out.println("linha 03 - PDF");
            }

        }
        distanciaTotal = distanciaTotal + distancia;
        /*if(i==0) {
         latAnt = Double.parseDouble(posicoes.get(i).get("lat"));
         lonAnt = Double.parseDouble(posicoes.get(i).get("lon"));
        } else{
            latAnt = Double.parseDouble(posicoes.get(i-1).get("lat"));
            lonAnt = Double.parseDouble(posicoes.get(i-1).get("lon"));
        }
        double latAtual = Double.parseDouble(posicoes.get(i).get("lat"));
        double lonAtual = Double.parseDouble(posicoes.get(i).get("lon"));
        double distancia = caculaDistanciaEntreDoisPontos(latAnt, lonAnt, latAtual, lonAtual);
        distanciaTotal = distanciaTotal + distancia;*/
        for (int col = 0; col < posicoes.get(linha).size(); col++) {
            XSSFCell cell = row.createCell(col);
            cell.setCellStyle(estiloCorpo);
            switch (col) {
            case 0:
                Date dataHora0 = new Date(Long.parseLong(posicoes.get(i).get("dataHora")));
                Date dataHora = new Date(dataHora0.getTime());
                SimpleDateFormat dataFormatada = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                dataFormatada.setTimeZone(timeZonePadrao);
                cell.setCellValue(dataFormatada.format(dataHora));
                break;
            case 1:
                cell.setCellValue(posicoes.get(linha).get("vel"));
                break;
            case 2:
                cell.setCellValue(
                        posicoes.get(linha).get("ign").equalsIgnoreCase("True") ? "Ligada" : "Desligada");
                break;
            /*case 3:
                cell.setCellValue(posicoes.get(linha).get("lat"));
                break;
            case 4:
                cell.setCellValue(posicoes.get(linha).get("lon"));
                break;
            case 5:
                cell.setCellValue(posicoes.get(linha).get("sat"));
                break;
            case 6:
                cell.setCellValue(posicoes.get(linha).get("gps"));
                break;
            case 7:
                cell.setCellValue(posicoes.get(linha).get("entrada"));
                break;
            case 8:
                cell.setCellValue(posicoes.get(linha).get("saida"));
                break;
            case 9:
                cell.setCellValue(posicoes.get(linha).get("evento"));
                break;*/
            case 3:
                cell.setCellValue(posicoes.get(linha).get("endereco") == null ? "Sem endereo"
                        : posicoes.get(linha).get("endereco"));
                break;
            /*case 11:
                cell.setCellValue(posicoes.get(linha).get("direcao"));
                break;*/
            }

        }
        j = j + 1;
        linha = linha + 1;

    }
    tempoDecorrido = calculaDatas(Long.parseLong(posicoes.get(0).get("dataHora")),
            Long.parseLong(posicoes.get(posicoes.size() - 1).get("dataHora")));
    int index = 0;
    String kms = "0";
    String m = "";
    double metros = 0;
    if (distanciaTotal > 0) {
        BigDecimal decimalFormatado = new BigDecimal(distanciaTotal).setScale(2, RoundingMode.HALF_EVEN);
        index = String.valueOf(decimalFormatado).indexOf(".");
        kms = String.valueOf(decimalFormatado).substring(0, index);
        m = "0" + (String.valueOf(decimalFormatado).substring(index));
        metros = Double.parseDouble(m) * 1000;
    }
    //String formatted = NumberFormat.getFormat("000.00").format(metros);
    //System.out.println("Percorridos aproximadamente : "+kms+" KM e "+metros+" metros");
    XSSFRow linhaX = (XSSFRow) sheet.createRow(linha + 12);
    XSSFCell cellX = linhaX.createCell(0);
    sheet.addMergedRegion(new CellRangeAddress(linha + 12, linha + 12, 0, 3));
    cellX.setCellStyle(estilo);
    cellX.setCellValue(
            "Percorridos: " + kms + " KM e " + String.valueOf(metros) + " metros. Tempo: " + tempoDecorrido);
    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
    wb.write(outByteStream);

    byte[] outArray = outByteStream.toByteArray();
    OutputStream outStream = response.getOutputStream();
    outStream.write(outArray);
    outStream.flush();

}

From source file:com.catexpress.util.FormatosPOI.java

public CellStyle estiloHeader(Workbook wb, int tipo) {
    Font fuente = wb.createFont();
    CreationHelper createHelper = wb.getCreationHelper();
    fuente.setFontName("Calibri");
    fuente.setBold(true);//  w w  w. ja  va2  s  .  com

    if (tipo == TITULO || tipo == SUCURSAL || tipo == LABEL || tipo == FECHA) {
        fuente.setFontHeightInPoints((short) 16);
    } else if (tipo == USUARIO) {
        fuente.setFontHeightInPoints((short) 20);
    }

    CellStyle estiloCelda = wb.createCellStyle();
    estiloCelda.setFont(fuente);

    if (tipo == TITULO || tipo == USUARIO || tipo == LABEL || tipo == FECHA) {
        estiloCelda.setFillForegroundColor(IndexedColors.WHITE.getIndex());
    } else if (tipo == SUCURSAL) {
        estiloCelda.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    }
    estiloCelda.setFillPattern(CellStyle.SOLID_FOREGROUND);

    if (tipo == LABEL || tipo == FECHA) {
        estiloCelda.setWrapText(false);
    } else if (tipo == TITULO || tipo == SUCURSAL || tipo == USUARIO) {
        estiloCelda.setWrapText(true);
    }

    estiloCelda.setAlignment(HorizontalAlignment.CENTER);

    if (tipo == LABEL || tipo == FECHA) {
        estiloCelda.setVerticalAlignment(VerticalAlignment.BOTTOM);
    } else if (tipo == TITULO || tipo == SUCURSAL || tipo == USUARIO) {
        estiloCelda.setVerticalAlignment(VerticalAlignment.CENTER);
    }

    if (tipo == SUCURSAL) {
        estiloCelda.setBorderBottom(BorderStyle.MEDIUM);
        estiloCelda.setBorderTop(BorderStyle.MEDIUM);
        estiloCelda.setBorderLeft(BorderStyle.MEDIUM);
        estiloCelda.setBorderRight(BorderStyle.MEDIUM);
    }

    if (tipo == FECHA) {
        estiloCelda.setDataFormat(createHelper.createDataFormat().getFormat("dd \"de\" mmmm \"de\" yyyy"));
    }

    return estiloCelda;
}

From source file:com.clican.pluto.dataprocess.engine.processes.ExcelProcessor.java

License:LGPL

@SuppressWarnings("unchecked")
public void writeExcel(ProcessorContext context, ExcelExecBean execBean) throws Exception {
    Workbook book = null;
    InputStream is = null;/*from  w  w  w . ja v  a 2s . c  o  m*/
    try {
        is = execBean.getInputStream();
    } catch (FileNotFoundException e) {

    }
    if (is != null) {
        book = WorkbookFactory.create(is);
        is.close();
    } else {
        book = new HSSFWorkbook();
    }
    CreationHelper createHelper = book.getCreationHelper();
    CellStyle dateStyle = book.createCellStyle();
    dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd"));

    CellStyle numStyle = book.createCellStyle();
    numStyle.setDataFormat(createHelper.createDataFormat().getFormat("0.00000000"));

    CellStyle intNumStyle = book.createCellStyle();
    intNumStyle.setDataFormat(createHelper.createDataFormat().getFormat("0"));

    List<Object> result = context.getAttribute(execBean.getParamName());
    String[] columns = execBean.getColumns();
    if (execBean.getColumns() != null) {
        columns = execBean.getColumns();
    } else {
        columns = ((List<String>) context.getAttribute(execBean.getColumnsVarName())).toArray(new String[] {});
    }
    String sheetName;
    if (StringUtils.isNotEmpty(execBean.getSheetName())) {
        sheetName = execBean.getSheetName();
    } else {
        sheetName = context.getAttribute(execBean.getSheetVarName()).toString();
    }
    // int number = book.getNumberOfSheets();
    Sheet sheet = book.createSheet(sheetName);
    int rowNum = 0;
    Row firstRow = sheet.createRow(rowNum++);
    for (int i = 0; i < columns.length; i++) {
        Cell cell = firstRow.createCell(i);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue(columns[i]);
    }

    for (int i = 0; i < result.size(); i++) {
        Object row = result.get(i);
        Row dataRow = sheet.createRow(rowNum++);

        for (int j = 0; j < columns.length; j++) {
            Object obj = PropertyUtils.getNestedProperty(row, columns[j]);
            Cell cell = dataRow.createCell(j);
            if (obj == null) {
                cell.setCellType(Cell.CELL_TYPE_BLANK);
            } else {
                if (obj instanceof String) {
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    cell.setCellValue(obj.toString());
                } else if (obj instanceof Date) {
                    cell.setCellValue((Date) obj);
                    cell.setCellStyle(dateStyle);
                } else if (obj instanceof Integer || obj instanceof Long) {
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellStyle(intNumStyle);
                    cell.setCellValue(new Double(obj.toString()));
                } else if (obj instanceof Number) {
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    cell.setCellStyle(numStyle);
                    cell.setCellValue(new Double(obj.toString()));
                } else {
                    throw new DataProcessException("??Excel?");
                }
            }
        }
    }

    OutputStream os = null;
    try {
        os = execBean.getOutputStream();
        book.write(os);
    } finally {
        if (os != null) {
            os.close();
        }
    }
}

From source file:com.company.et.service.XlsService.java

public static void generateFile(List<TreeItem<Task>> root, List<ArrayList<ArrayList<Double>>> waitingParts,
        ObservableList<Professor> professors) throws FileNotFoundException, IOException {
    FileOutputStream out = new FileOutputStream(filename);
    Workbook wb = new HSSFWorkbook();

    for (int k = 0; k < professors.size(); k++) {

        Sheet s = wb.createSheet(professors.get(k).getFio());

        Row rowFirst = s.createRow(0);// w  ww  . j a v a  2s  .  c  om

        createConstStringCells(wb, s, "??", rowFirst, 0, 0, 1, 0, 0);
        createConstStringCells(wb, s, "?? ", rowFirst, 1, 0, 0, 1, 3);
        createConstStringCells(wb, s, "? ", rowFirst, 4, 0, 0, 4, 6);
        createConstStringCells(wb, s, "?? ", rowFirst, 7, 0, 0, 7, 9);
        createConstStringCells(wb, s, "?? ", rowFirst, 10, 0, 0, 10, 12);
        createConstStringCells(wb, s, "?? ", rowFirst, 13, 0, 0, 13, 15);

        Row rowSecond = s.createRow(1);
        for (int i = 0, j = 1; i < 5; i++, j += 3) {
            createConstStringCells(wb, s, "", rowSecond, j, 0, 0, 0, 0);
            createConstStringCells(wb, s, "", rowSecond, j + 1, 0, 0, 0, 0);
            createConstStringCells(wb, s, "", rowSecond, j + 2, 0, 0, 0, 0);
        }

        for (int i = 1; i < 16; i++) {
            Row row = s.createRow(i + 1);
            for (int j = 0; j < root.get(k).getChildren().size(); j++) {
                createCellOfDouble(wb, s, row, j * 3 + 2,
                        root.get(k).getChildren().get(j).getValue().getCapacities().get(i));
                createCellOfDouble(wb, s, row, j * 3 + 1, waitingParts.get(k).get(j).get(i));
                createReserveCell(wb, s, row, (j + 1) * 3);

            }
            createMonthCell(wb, s, row, DoubleCapacities.getDoubleCapacitiesByIndex(i).toString());
            createFullTasksActualCell(wb, s, row, root.get(k).getChildren().size() * 3 + 1);
            createFullTasksCell(wb, s, row, root.get(k).getChildren().size() * 3 + 2);
            createFullTasksReserveCell(wb, s, row, (root.get(k).getChildren().size() + 1) * 3);

        }
    }
    FormulaEvaluator formulaEval = wb.getCreationHelper().createFormulaEvaluator();
    //all year report
    Sheet s = wb.createSheet("?");
    Row rowFirst = s.createRow(0);
    Row rowSecond = s.createRow(1);
    createConstStringCells(wb, s, "/", rowFirst, 0, 0, 1, 0, 0);
    createConstStringCells(wb, s, "", rowFirst, 1, 0, 1, 1, 1);
    createConstStringCells(wb, s, "?", rowFirst, 2, 0, 1, 2, 2);
    createConstStringCells(wb, s, ". .", rowFirst, 3, 0, 1, 3, 3);
    for (int i = 1; i < 16; i++) {
        createConstStringCells(wb, s, DoubleCapacities.getDoubleCapacitiesByIndex(i).toString(), rowFirst,
                (i * 3) + 1, 0, 0, (i * 3) + 1, (i * 3) + 3);
        createConstStringCells(wb, s, "", rowSecond, (i * 3) + 1, 1, 1, (i * 3) + 1, (i * 3) + 1);
        createConstStringCells(wb, s, "", rowSecond, (i * 3) + 2, 1, 1, (i * 3) + 2, (i * 3) + 2);
        createConstStringCells(wb, s, "", rowSecond, (i * 3) + 3, 1, 1, (i * 3) + 3, (i * 3) + 3);
    }
    for (int i = 0; i < professors.size(); i++) {
        Row row = s.createRow(i + 2);
        createConstStringCells(wb, s, Integer.toString(i + 1), row, 0, i + 2, i + 2, 0, 0);
        createConstStringCells(wb, s, professors.get(i).getFio(), row, 1, i + 2, i + 2, 1, 1);
        createConstStringCells(wb, s, professors.get(i).getRate().toString(), row, 3, i + 2, i + 2, 3, 3);
        for (int j = 1; j < 16; j++) {
            createConstStringCells(wb, s,
                    formulaEval.evaluate(wb.getSheet(professors.get(i).getFio()).getRow(j + 1).getCell(13))
                            .formatAsString(),
                    row, (j * 3) + 1, i + 2, i + 2, (j * 3) + 1, (j * 3) + 1);
            createConstStringCells(wb, s,
                    formulaEval.evaluate(wb.getSheet(professors.get(i).getFio()).getRow(j + 1).getCell(14))
                            .formatAsString(),
                    row, (j * 3) + 2, i + 2, i + 2, (j * 3) + 2, (j * 3) + 2);
            createConstStringCells(wb, s,
                    formulaEval.evaluate(wb.getSheet(professors.get(i).getFio()).getRow(j + 1).getCell(15))
                            .formatAsString(),
                    row, (j * 3) + 3, i + 2, i + 2, (j * 3) + 3, (j * 3) + 3);
        }
    }
    wb.write(out);

    out.close();

}

From source file:com.dituiba.excel.DefaultOutputAdapter.java

License:Apache License

/**
 * ?/*from  ww  w.j a  va  2 s .c  om*/
 *
 * @param fieldValue
 * @param fieldName
 * @return
 * @throws AdapterException
 */
public void outputDateAdapter(DataBean dataBean, Object fieldValue, String fieldName, Cell cell)
        throws AdapterException {
    log.debug("in DefaultOutputAdapter:outputDateAdapter fieldName:{} fieldValue:{}", fieldName, fieldValue);
    Date date = null;
    if (fieldValue == null) {
        log.debug("fieldValue is null return");
        cell.setCellValue("");
        return;
    } else if (fieldValue instanceof Date) {
        log.debug("fieldValue instanceof Date ");
        date = (Date) fieldValue;
    } else if (fieldValue instanceof String) {
        log.debug("fieldValue instanceof String ");
        InputDateConfig config = dataBean.getInputConfig(fieldName);
        try {
            date = DateUtil.formatToDate((String) fieldValue, config.format());
        } catch (ParseException e) {
            throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell);
        }
    } else if (fieldValue instanceof Long) {
        log.debug("fieldValue instanceof Long ");
        date = new Date((Long) fieldValue);
    } else {
        throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell);
    }
    Workbook workbook = cell.getSheet().getWorkbook();
    OutputDateConfig outputConfig = dataBean.getOutputConfig(fieldName);
    CellStyle cellStyle = cell.getCellStyle();
    if (cellStyle == null)
        cellStyle = workbook.createCellStyle();
    CreationHelper createHelper = workbook.getCreationHelper();
    cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(outputConfig.format()));
    cell.setCellStyle(cellStyle);
    cell.setCellValue(date);
}

From source file:com.dituiba.excel.DefaultOutputAdapter.java

License:Apache License

public void outputNumericAdapter(DataBean dataBean, Object fieldValue, String fieldName, Cell cell)
        throws AdapterException {
    log.debug("in DefaultOutputAdapter:outputNumericAdapter fieldName:{} fieldValue:{}", fieldName, fieldValue);
    if (ObjectHelper.isNullOrEmptyString(fieldValue))
        return;/*from ww  w.  ja  v  a2s  .  c o m*/
    OutputNumericConfig config = dataBean.getOutputConfig(fieldName);
    Workbook workbook = cell.getSheet().getWorkbook();
    CellStyle cellStyle = workbook.createCellStyle();
    CreationHelper createHelper = workbook.getCreationHelper();
    StringBuilder format = new StringBuilder("0");
    for (int i = 0; i < config.floatCount(); i++) {
        if (i == 0)
            format.append(".");
        format.append("0");
    }
    cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(format.toString()));
    cell.setCellValue(NumberUtils.format(fieldValue, config.floatCount()));
    cell.setCellStyle(cellStyle);
}