Example usage for org.apache.poi.hssf.usermodel HSSFWorkbook write

List of usage examples for org.apache.poi.hssf.usermodel HSSFWorkbook write

Introduction

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

Prototype

private void write(POIFSFileSystem fs) throws IOException 

Source Link

Document

Writes the workbook out to a brand new, empty POIFS

Usage

From source file:com.ibm.ioes.bulkupload.utilities.ErrorLogServiceImpl.java

public String getTemplate(String filePath, int templateId) throws IOESException, ParseException {
    //logger.info(" Entered into getErrorExcel method of " + this.getClass().getSimpleName());

    String fileName;//from  w ww.  j  av  a 2  s. com
    HSSFWorkbook wb;
    HSSFSheet ws;
    HSSFRow wr;
    HSSFCell wc;
    ArrayList filledTemplateData = new ArrayList();
    ErrorFileDaoImpl objDao = new ErrorFileDaoImpl();
    ViewOrderModel objviewmodel = new ViewOrderModel();
    //ErrorLogDto dtoObj ;
    TransactionTemplateDto dtoObj;
    ViewOrderDto dtoObj1;
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    int totalRowsOfSheet = 0;
    ViewOrderDto objdto = null;
    String str = null;
    try {
        ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources");

        fileName = filePath.substring((filePath.lastIndexOf("/") + 1), filePath.length());
        String newFile = bundle.getString("excel.filledTemplate") + "/" + fileName;
        FileOutputStream fileOut = new FileOutputStream(newFile);
        wb = new HSSFWorkbook(new FileInputStream(filePath));
        HSSFCellStyle whiteFG_yellow = wb.createCellStyle();

        HSSFColor yellow = setColor(wb, (byte) 0xFF, (byte) 0xFF, (byte) 0x00);
        //whiteFG_yellow.setFillBackgroundColor(HSSFColor.YELLOW.index);
        whiteFG_yellow.setFillBackgroundColor(yellow.getIndex());

        HSSFCellStyle whiteFG_green = wb.createCellStyle();
        HSSFColor green = setColor(wb, (byte) 0x00, (byte) 0xFF, (byte) 0x00);
        //whiteFG_green.setFillBackgroundColor(HSSFColor.GREEN.index);
        whiteFG_green.setFillBackgroundColor(green.getIndex());

        //System.out.println(filledTemplateData.toString());
        //System.out.println(wb.getNumberOfSheets());

        for (int s = 0; s < wb.getNumberOfSheets(); s++) {
            ws = wb.getSheetAt(s);
            if (s == 0 && (templateId == 1)) {
                int ctr = 0, totalRowsOfSheetMain = 0, totalRowsOfSheetAtt = 0;
                //filledTemplateData = objDao.getFilledTemplate(s+1,templateId,flag);
                for (int r = 2; r <= (totalRowsOfSheetMain + 1); r++) {
                    dtoObj = (TransactionTemplateDto) filledTemplateData.get(ctr);
                    wr = ws.createRow(r);
                    if (wr != null) {
                        wr.createCell(1).setCellValue(dtoObj.getOrderNo());
                        wr.createCell(2).setCellValue(new HSSFRichTextString((dtoObj.getAccountID())));
                        wr.createCell(3).setCellValue(new HSSFRichTextString((dtoObj.getSource())));
                        wr.createCell(4).setCellValue(new HSSFRichTextString((dtoObj.getCurrencyID())));
                        wr.createCell(5).setCellValue(new HSSFRichTextString((dtoObj.getOpportunityId())));
                        wr.createCell(6).setCellValue(new HSSFRichTextString((dtoObj.getQuoteNo())));
                        wr.createCell(7).setCellValue(new HSSFRichTextString((dtoObj.getProjectMangerID())));
                        wr.createCell(8).setCellValue(new HSSFRichTextString((dtoObj.getZoneId())));
                    }
                    ctr++;
                }
            }
            wb.write(fileOut);
            fileOut.close();
            filePath = newFile;
        }
    } catch (IOException ioExp) {
        //logger.error(ioExp.getMessage() + " Exception occured in getErrorExcel method of " + this.getClass().getSimpleName());
        //throw new IOESException("SQL Exception : "+ ioExp.getMessage(), ioExp);
        Utility.LOG(true, false, ioExp, "::BULKUPLOAD_ERROR::Exception occured in getTemplate method of "
                + this.getClass().getSimpleName());
        return filePath = "NOTFOUND";
    }
    return filePath;
}

From source file:com.ibm.ioes.bulkupload.utilities.ErrorLogServiceImpl.java

public String getResultErrorMixLog(String filePath, int fileID) throws IOESException {
    //logger.info(" Entered into getErrorExcel method of " + this.getClass().getSimpleName());

    int colCount, ctr = 0;
    String fileName;// www. j a  v a2 s  .co  m
    HSSFWorkbook wb;
    HSSFSheet ws;
    HSSFRow wr;
    HSSFCell wc;
    ArrayList errVal = new ArrayList();
    ErrorFileDaoImpl objDao = new ErrorFileDaoImpl();
    ErrorLogDto dtoObj;

    try {
        ResourceBundle bundle = ResourceBundle.getBundle("ApplicationResources");

        fileName = filePath.substring((filePath.lastIndexOf("/") + 1), filePath.length());
        String newFile = bundle.getString("excel.success") + "/" + fileName;
        FileOutputStream fileOut = new FileOutputStream(newFile);
        wb = new HSSFWorkbook(new FileInputStream(filePath));

        errVal = objDao.getResultErrorMixLog(fileID);
        System.out.println(errVal.toString());
        System.out.println(wb.getNumberOfSheets());

        HSSFCellStyle styleErr = wb.createCellStyle();
        HSSFCellStyle styleSuccess = wb.createCellStyle();
        HSSFFont fontSuccess = wb.createFont();
        HSSFFont fontErr = wb.createFont();

        for (int s = 0; s < wb.getNumberOfSheets(); s++) {

            ws = wb.getSheetAt(s);
            wr = ws.getRow(1);
            colCount = wr.getLastCellNum();
            wc = wr.createCell(colCount);
            wc.setCellValue("RESULT LOG" + "_" + "ORDERNO");

            for (int r = 2; r <= ws.getLastRowNum(); r++) {
                if ((ctr < errVal.size())) {
                    dtoObj = (ErrorLogDto) errVal.get(ctr);
                    wr = ws.getRow(r);
                    if (wr != null) {
                        int chk = 0;
                        for (int col = 0; col < colCount; col++) {
                            wc = wr.getCell(col);
                            if (wc != null) {
                                if (!(wc.toString().trim().equals(""))) {
                                    chk = 1;
                                }
                            }
                        }
                        if (chk == 1) {
                            wc = wr.createCell(colCount);
                            if ((dtoObj.getResultLogValue() == null || dtoObj.getResultLogValue().length() == 0)
                                    && dtoObj.getErrorLogValue() != null) {
                                fontErr.setColor(HSSFColor.RED.index);
                                styleErr.setFont(fontErr);
                                wc.setCellStyle(styleErr);
                                wc.setCellValue(dtoObj.getErrorLogValue().toString());
                            } else {
                                fontSuccess.setColor(HSSFColor.BLACK.index);
                                styleSuccess.setFont(fontSuccess);
                                wc.setCellStyle(styleSuccess);
                                wc.setCellValue(dtoObj.getResultLogValue().toString());
                            }

                            ctr++;
                        }
                    }
                }
            }
        }
        wb.write(fileOut);
        fileOut.close();
        filePath = newFile;
    } catch (IOESException ex) {
        logger.error(ex.getMessage() + " Exception occured in getResultExcel method of "
                + this.getClass().getSimpleName());
        throw new IOESException("SQL Exception : " + ex.getMessage(), ex);
    } catch (IOException ioExp) {
        //logger.error(ioExp.getMessage() + " Exception occured in getErrorExcel method of " + this.getClass().getSimpleName());
        //throw new IOESException("SQL Exception : "+ ioExp.getMessage(), ioExp);
        return filePath = "NOTFOUND";
    }
    return filePath;
}

From source file:com.ibm.tap.misld.batch.MassNotificationBatch.java

public void sendNotify() {

    String reportTemplateFilename = null;

    reportTemplateFilename = "Microsoft_Hardware_Scan_Template.xls";

    try {//from w  w w  .j  a  va  2  s  .co  m
        setFrom("HARDWARE-SCAN-REPORT");
        setSubject("Hardware scan report for: " + customer.getCustomerName());
        setTo(customer.getContactDPE().getRemoteUser());
    } catch (Exception e) {
        logMsg(e);
    }
    try {
        XlsReport xlsReport = new XlsReport(reportTemplateFilename, customer, null);

        xlsReport.setXlsReport(MsHardwareBaselineReadDelegate.getScanReport(customer));

        XlsReportGenerator xlsReportGenerator = new XlsReportGenerator();
        HSSFWorkbook wb = xlsReportGenerator.buildXlsReport(xlsReport);

        if (wb != null) {
            FileOutputStream fileOut = null;
            String fileOutName = "hardware_scan_report_" + this.customer.getAccountNumber() + ".xls";

            fileOut = new FileOutputStream(Constants.SPREAD_IN + fileOutName);
            wb.write(fileOut);
            fileOut.close();

            addBody("DPE, \n\n");

            addBody("Attached is a spreadsheet that contains the time that we last scanned your in-scope Windows servers for SPLA/ESPLA license reporting.  This spreadsheet should contain the hostnames for any servers that have a Microsoft operating system or any other Microsoft products which IBM is responsible licensing.  Please look at this spreadsheet and verify that the IBM provided Microsoft products utilized on your account have not changed (added, removed, updated) since the last scan date.\n\n");

            addBody("Any servers using Microsoft Software that have been added or changed since the last scan date must be scanned for a Microsoft software inventory.  If updates are required and there is currently not an automated scanning agent in place on your account, please follow this procedure to ensure your servers are reported correctly:\n");
            addBody("- Set change Windows for the SW inventory scan.\n");
            addBody("- Engage your server support team to run software inventory scan.\n");
            addBody("- Ensure inventory scans are completed and output files have been sent to the inventory server.\n\n");
            addBody("The SW inventory script(w32-ix86.zip) and scanning procedure and documentation (standalone.pdf) can be downloaded from this link:  http://tap.raleigh.ibm.com/standalone/ .\n\n");
            addBody("If you need help or have any questions, please contact your software asset management representative.\n\n");
            addAttachment(Constants.SPREAD_IN + fileOutName);
            sendMsg(remoteUser);
        }

        NotificationDelegate.createNotification(customer, remoteUser, "SCAN");
    } catch (Exception e) {
        e.printStackTrace();
        logMsg(e);
    }
}

From source file:com.ideaspymes.arthyweb.ventas.web.controllers.VentasCantadasBean.java

public void generarExcelVentasCantadas() throws IOException {

    cargaResumen();/*w w w  .j  a v  a 2s .  c  o  m*/

    if (ventasCantadas == null || ventasCantadas.isEmpty()) {
        JsfUtil.addErrorMessage("No hay datos para generar");
    } else {
        Map<String, List<ResumenVentasCantadas>> map2 = new HashMap<>();

        for (ResumenVentasCantadas rc : ventasCantadas) {
            List<ResumenVentasCantadas> valueList = map2.get(rc.getTerritorio());
            if (valueList == null) {
                valueList = new ArrayList<>();
                valueList.add(rc);
                map2.put(rc.getTerritorio(), valueList);
            } else {
                valueList.add(rc);
            }
        }

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Ventas Detalle");

        configAnchoCols(sheet);

        //Fonts
        Font fontSubTitulo = workbook.createFont();
        fontSubTitulo.setFontHeightInPoints((short) 8);
        fontSubTitulo.setBoldweight(Font.BOLDWEIGHT_BOLD);

        //Fonts
        Font fontTotal3 = workbook.createFont();
        fontTotal3.setFontHeightInPoints((short) 8);
        fontTotal3.setColor(HSSFColor.RED.index);
        fontTotal3.setBoldweight(Font.BOLDWEIGHT_BOLD);

        //Fonts
        Font fontTerritorioTotal3 = workbook.createFont();
        fontTerritorioTotal3.setFontHeightInPoints((short) 8);
        fontTerritorioTotal3.setColor(HSSFColor.ORANGE.index);
        fontTerritorioTotal3.setBoldweight(Font.BOLDWEIGHT_BOLD);

        //Estilos
        DataFormat format = workbook.createDataFormat();
        CellStyle styleTotal3 = workbook.createCellStyle();

        styleTotal3.setFont(fontTotal3);
        styleTotal3.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
        styleTotal3.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
        styleTotal3.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
        styleTotal3.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
        styleTotal3.setDataFormat(format.getFormat("0.0%"));

        styleTerritorioTotal3 = workbook.createCellStyle();
        styleTerritorioTotal3.setFont(fontTerritorioTotal3);
        styleTerritorioTotal3.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
        styleTerritorioTotal3.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
        // styleTerritorioTotal3.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
        // styleTerritorioTotal3.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

        creaCabecera(workbook, sheet);

        String[] aCols20 = null;
        String[] aCols10 = null;
        String[] aColsGrue = null;
        String indicesTotales = "";

        for (Map.Entry<String, List<ResumenVentasCantadas>> entry : map2.entrySet()) {
            ++indexRow;

            HSSFRow row = sheet.createRow((++indexRow));

            HSSFCell cellTerr = row.createCell(indexCol);
            cellTerr.setCellValue(entry.getKey().toUpperCase());
            cellTerr.setCellStyle(styleTerritorio);

            int indexInicioGrupo = indexRow + 2;

            List<ResumenVentasCantadas> detalles = entry.getValue();

            Comparator<ResumenVentasCantadas> comp = new Comparator<ResumenVentasCantadas>() {

                @Override
                public int compare(ResumenVentasCantadas o1, ResumenVentasCantadas o2) {
                    return o1.getOrden() > o2.getOrden() ? 1 : -1;
                }
            };

            Collections.sort(detalles, comp);

            for (ResumenVentasCantadas rv : detalles) {
                cols20 = "";
                cols10 = "";
                colsGrue = "";

                int indexFilaActual = ++indexRow;
                HSSFRow row1 = sheet.createRow((indexFilaActual));

                HSSFCell cellZona = row1.createCell(indexCol + 0);
                cellZona.setCellValue(rv.getZona());
                cellZona.setCellStyle(styleTitulo9);

                HSSFCell cellVendedor = row1.createCell(indexCol + 1);
                cellVendedor.setCellValue(rv.getVendedor());
                cellVendedor.setCellStyle(styleTitulo9);

                HSSFCell cellBoletas = row1.createCell(indexCol + 2);
                cellBoletas.setCellValue(rv.getCantboletas());
                cellBoletas.setCellStyle(styleCantidad);

                generarDetalles(row1, indexFilaActual, rv);

            }

            int indexFinGrupo = indexRow + 1;

            int indexTotal1 = ++indexRow;
            int indexTotal2 = ++indexRow;
            int indexTotal3 = ++indexRow;

            HSSFRow rowTotal1 = sheet.createRow(indexTotal1);
            HSSFRow rowTotal2 = sheet.createRow((indexTotal2));
            HSSFRow rowTotal3 = sheet.createRow((indexTotal3));

            aCols20 = cols20.split(",");
            aCols10 = cols10.split(",");
            aColsGrue = colsGrue.split(",");

            //TOTAL 1
            generarTotal1(rowTotal1, indexInicioGrupo, indexFinGrupo, aColsGrue, aCols20, aCols10, cellTerr);
            //TOTAL 2
            generarTotal2(rowTotal2, indexFinGrupo, aColsGrue, cellTerr);
            //TOTAL 3
            generarTotal3(rowTotal3, indexFinGrupo, styleTotal3, cellTerr, sheet);
            //++indexRow;

            indicesTotales += (indexFinGrupo + 1) + ",";
        }

        String[] aIndexTotales = indicesTotales.split(",");

        //TOTAL pais
        int indexTotalPais = ++indexRow;
        HSSFRow rowTotalPais = sheet.createRow((indexTotalPais));
        generarTotalPais(rowTotalPais, styleTotal3, sheet, aIndexTotales, aColsGrue, aCols20, aCols10);

        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=Ventas Cantadas.xls");
        workbook.write(response.getOutputStream());
        response.getOutputStream().flush();
        response.getOutputStream().close();
        FacesContext.getCurrentInstance().responseComplete();
        indexRow = 1;
    }

}

From source file:com.ideaspymes.arthyweb.ventas.web.controllers.VentasCantadasBean.java

public void generarExcelVentasCantadasDetalle() throws IOException {

    cargaResumenPorVendedor();/*from ww  w. j  a v  a2 s.  com*/

    if (ventasCantadas == null || ventasCantadas.isEmpty()) {
        JsfUtil.addErrorMessage("No hay datos para generar");
    } else {
        Map<String, List<ResumenVentasCantadas>> map2 = new HashMap<>();

        for (ResumenVentasCantadas rc : ventasCantadas) {
            List<ResumenVentasCantadas> valueList = map2.get(rc.getTerritorio());
            if (valueList == null) {
                valueList = new ArrayList<>();
                valueList.add(rc);
                map2.put(rc.getTerritorio(), valueList);
            } else {
                valueList.add(rc);
            }
        }

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Ventas Detalle");

        configAnchoCols(sheet);

        //Fonts
        Font fontSubTitulo = workbook.createFont();
        fontSubTitulo.setFontHeightInPoints((short) 8);
        fontSubTitulo.setBoldweight(Font.BOLDWEIGHT_BOLD);

        //Fonts
        Font fontTotal3 = workbook.createFont();
        fontTotal3.setFontHeightInPoints((short) 8);
        fontTotal3.setColor(HSSFColor.RED.index);
        fontTotal3.setBoldweight(Font.BOLDWEIGHT_BOLD);

        //Fonts
        Font fontTerritorioTotal3 = workbook.createFont();
        fontTerritorioTotal3.setFontHeightInPoints((short) 8);
        fontTerritorioTotal3.setColor(HSSFColor.ORANGE.index);
        fontTerritorioTotal3.setBoldweight(Font.BOLDWEIGHT_BOLD);

        //Estilos
        DataFormat format = workbook.createDataFormat();
        CellStyle styleTotal3 = workbook.createCellStyle();

        styleTotal3.setFont(fontTotal3);
        styleTotal3.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
        styleTotal3.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
        styleTotal3.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
        styleTotal3.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
        styleTotal3.setDataFormat(format.getFormat("0.0%"));

        styleTerritorioTotal3 = workbook.createCellStyle();
        styleTerritorioTotal3.setFont(fontTerritorioTotal3);
        styleTerritorioTotal3.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
        styleTerritorioTotal3.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
        // styleTerritorioTotal3.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
        // styleTerritorioTotal3.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);

        creaCabecera(workbook, sheet);

        String[] aCols20 = null;
        String[] aCols10 = null;
        String[] aColsGrue = null;
        String indicesTotales = "";

        for (Map.Entry<String, List<ResumenVentasCantadas>> entry : map2.entrySet()) {
            ++indexRow;

            HSSFRow row = sheet.createRow((++indexRow));

            HSSFCell cellTerr = row.createCell(indexCol);
            cellTerr.setCellValue(entry.getKey().toUpperCase());
            cellTerr.setCellStyle(styleTerritorio);

            int indexInicioGrupo = indexRow + 2;

            List<ResumenVentasCantadas> detalles = entry.getValue();

            Comparator<ResumenVentasCantadas> comp = new Comparator<ResumenVentasCantadas>() {

                @Override
                public int compare(ResumenVentasCantadas o1, ResumenVentasCantadas o2) {
                    return o1.getOrden() > o2.getOrden() ? 1 : -1;
                }
            };

            Collections.sort(detalles, comp);

            for (ResumenVentasCantadas rv : detalles) {
                cols20 = "";
                cols10 = "";
                colsGrue = "";

                int indexFilaActual = ++indexRow;
                HSSFRow row1 = sheet.createRow((indexFilaActual));

                HSSFCell cellZona = row1.createCell(indexCol + 0);
                cellZona.setCellValue(rv.getZona());
                cellZona.setCellStyle(styleTitulo9);

                HSSFCell cellVendedor = row1.createCell(indexCol + 1);
                cellVendedor.setCellValue(rv.getVendedor());
                cellVendedor.setCellStyle(styleTitulo9);

                HSSFCell cellBoletas = row1.createCell(indexCol + 2);
                cellBoletas.setCellValue(rv.getCantboletas());
                cellBoletas.setCellStyle(styleCantidad);

                generarDetalles(row1, indexFilaActual, rv);

            }

            int indexFinGrupo = indexRow + 1;

            int indexTotal1 = ++indexRow;
            int indexTotal2 = ++indexRow;
            int indexTotal3 = ++indexRow;

            HSSFRow rowTotal1 = sheet.createRow(indexTotal1);
            HSSFRow rowTotal2 = sheet.createRow((indexTotal2));
            HSSFRow rowTotal3 = sheet.createRow((indexTotal3));

            aCols20 = cols20.split(",");
            aCols10 = cols10.split(",");
            aColsGrue = colsGrue.split(",");

            //TOTAL 1
            generarTotal1(rowTotal1, indexInicioGrupo, indexFinGrupo, aColsGrue, aCols20, aCols10, cellTerr);
            //TOTAL 2
            generarTotal2(rowTotal2, indexFinGrupo, aColsGrue, cellTerr);
            //TOTAL 3
            generarTotal3(rowTotal3, indexFinGrupo, styleTotal3, cellTerr, sheet);
            //++indexRow;

            indicesTotales += (indexFinGrupo + 1) + ",";
        }

        String[] aIndexTotales = indicesTotales.split(",");

        //TOTAL pais
        int indexTotalPais = ++indexRow;
        HSSFRow rowTotalPais = sheet.createRow((indexTotalPais));
        generarTotalPais(rowTotalPais, styleTotal3, sheet, aIndexTotales, aColsGrue, aCols20, aCols10);

        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                .getExternalContext().getResponse();

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=Ventas Cantadas.xls");
        workbook.write(response.getOutputStream());
        response.getOutputStream().flush();
        response.getOutputStream().close();
        FacesContext.getCurrentInstance().responseComplete();
        indexRow = 1;
    }

}

From source file:com.idega.block.datareport.business.SimpleReportBusinessBean.java

License:Open Source License

public void writeSimpleExcelFile(JRDataSource reportData, String nameOfReport, String filePathAndName,
        ReportDescription description) throws IOException {
    if (nameOfReport == null || "".equals(nameOfReport)) {
        nameOfReport = NAME_OF_REPORT;//from w  w w .  j  a  v a  2s. com
    }
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet(TextSoap.encodeToValidExcelSheetName(nameOfReport));
    int rowIndex = 0;

    //-- Report Name --//
    // Create a row and put some cells in it. Rows are 0 based.
    HSSFRow row = sheet.createRow((short) rowIndex++);
    // Create a cell and put a value in it.
    HSSFCell cell = row.createCell((short) 0);

    // Create a new font and alter it.
    HSSFFont font = wb.createFont();
    font.setFontHeightInPoints((short) 24);
    font.setFontName(REPORT_FONT);
    font.setItalic(true);
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

    // Fonts are set into a style so create a new one to use.
    HSSFCellStyle style = wb.createCellStyle();
    style.setFont(font);

    // Create a cell and put a value in it.
    cell.setCellValue(nameOfReport);
    cell.setCellStyle(style);

    //-- Report Parameters --//
    rowIndex++;
    HSSFRow row1 = null;
    String parameterString = "";
    List labels = description.getListOfHeaderParameterLabelKeys();
    List parameters = description.getListOfHeaderParameterKeys();
    Iterator labelIter = labels.iterator();
    Iterator parameterIter = parameters.iterator();
    boolean newLineForeEachParameter = description.doCreateNewLineForEachParameter();
    while (labelIter.hasNext() && parameterIter.hasNext()) {
        String label = description.getParameterOrLabelName((String) labelIter.next());
        String parameter = description.getParameterOrLabelName((String) parameterIter.next());
        if (newLineForeEachParameter) {
            row1 = sheet.createRow((short) rowIndex++);
            row1.createCell((short) 0).setCellValue(label + " " + parameter);
        } else {
            parameterString += label + " " + parameter + "      ";
        }
    }
    if (!newLineForeEachParameter) {
        row1 = sheet.createRow((short) rowIndex++);
        row1.createCell((short) 0).setCellValue(parameterString);
    }
    rowIndex++;

    //-- Report ColumnHeader --//
    List fields = description.getListOfFields();
    HSSFRow headerRow = sheet.createRow((short) rowIndex++);

    HSSFCellStyle headerCellStyle = wb.createCellStyle();

    headerCellStyle.setWrapText(true);
    headerCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
    headerCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);

    HSSFFont headerCellFont = wb.createFont();
    //headerCellFont.setFontHeightInPoints((short)12);
    headerCellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    headerCellStyle.setFont(headerCellFont);

    int colIndex = 0;
    int columnWithUnit = 256; // the unit is 1/256 of a character
    int numberOfCharactersPerLineInLongTextFields = 60;
    int numberOfCharactersPerLineInRatherLongTextFields = 35;
    int numberOfCharactersPerLineInUndifinedTextFields = 20;

    for (Iterator iter = fields.iterator(); iter.hasNext(); colIndex++) {
        ReportableField field = (ReportableField) iter.next();
        HSSFCell headerCell = headerRow.createCell((short) colIndex);
        headerCell.setCellValue(description.getColumnName(field));
        headerCell.setCellStyle(headerCellStyle);

        //column width
        int fieldsMaxChar = field.getMaxNumberOfCharacters();
        int colWith = numberOfCharactersPerLineInRatherLongTextFields * columnWithUnit; //default, can be rather long text
        if (fieldsMaxChar > 0 && fieldsMaxChar < numberOfCharactersPerLineInRatherLongTextFields) {
            colWith = (fieldsMaxChar + 1) * columnWithUnit; // short fields
        } else if (fieldsMaxChar > 500) { // when the field is set to be able to contain very long text
            colWith = numberOfCharactersPerLineInLongTextFields * columnWithUnit; //can be very long text
        } else if (fieldsMaxChar < 0) {
            colWith = numberOfCharactersPerLineInUndifinedTextFields * columnWithUnit;
        }
        sheet.setColumnWidth((short) colIndex, (short) colWith);

    }

    //-- Report ColumnDetail --//
    try {
        HSSFCellStyle dataCellStyle = wb.createCellStyle();
        dataCellStyle.setWrapText(true);
        dataCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
        sheet.createFreezePane(0, rowIndex);

        while (reportData.next()) {
            HSSFRow dataRow = sheet.createRow((short) rowIndex++);
            colIndex = 0;
            for (Iterator iter = fields.iterator(); iter.hasNext(); colIndex++) {
                ReportableField field = (ReportableField) iter.next();
                HSSFCell dataCell = dataRow.createCell((short) colIndex);
                Object fieldValue = reportData.getFieldValue(field);
                if (fieldValue != null) {
                    dataCell.setCellValue(String.valueOf(fieldValue));
                }
                dataCell.setCellStyle(dataCellStyle);
            }
        }
    } catch (JRException e) {
        //-- Exception fetching data --//
        HSSFRow exceptionRow = sheet.createRow((short) rowIndex++);
        HSSFCell exceptionCell = exceptionRow.createCell((short) 0);

        // Create a new font and alter it.
        HSSFFont exceptionFont = wb.createFont();
        exceptionFont.setFontName(REPORT_FONT);
        exceptionFont.setItalic(true);

        // Fonts are set into a style so create a new one to use.
        HSSFCellStyle exceptionStyle = wb.createCellStyle();
        exceptionStyle.setFont(exceptionFont);

        // Create a cell and put a value in it.
        exceptionCell.setCellValue("Error occurred while getting data. Check log for more details.");
        exceptionCell.setCellStyle(exceptionStyle);

        e.printStackTrace();
    }

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream(filePathAndName);
    wb.write(fileOut);
    fileOut.close();
}

From source file:com.inkubator.common.util.NewMain.java

/**
 * @param args the command line arguments
 *///from   w  w  w .  jav a 2s. co  m
public static void main(String[] args) throws IOException {

    File file1 = new File(
            "C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\JSON_Ek\\Surabaya\\Page1.txt");
    File file2 = new File(
            "C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\JSON_Ek\\Surabaya\\Page2.txt");
    //        File file3 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\json\\json\\menado\\page3.txt");
    File file3 = new File(
            "C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\JSON_Ek\\Surabaya\\Page3.txt");
    File file4 = new File(
            "C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\JSON_Ek\\Surabaya\\Page4.txt");
    File file5 = new File(
            "C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\JSON_Ek\\Surabaya\\Page5.txt");
    File file6 = new File(
            "C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\JSON_Ek\\Surabaya\\Page6.txt");
    //        File file7 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 7.txt");
    //        File file8 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 8.txt");
    //        File file9 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 9.txt");
    //        File file10 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 10.txt");
    //        File file11 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 11.txt");
    //        File file12 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 12.txt");
    //        File file13 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 13.txt");
    //        File file14 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 14.txt");
    //        File file15 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 15.txt");
    //        File file16 = new File("C:\\Users\\deni.fahri\\Downloads\\page16.txt");

    //        File file2 = new File("C:\\Users\\deni.fahri\\Documents\\hasil.txt");
    String agoda = FilesUtil.getAsStringFromFile(file1);
    String agoda1 = FilesUtil.getAsStringFromFile(file2);
    String agoda2 = FilesUtil.getAsStringFromFile(file3);
    String agoda3 = FilesUtil.getAsStringFromFile(file4);
    String agoda4 = FilesUtil.getAsStringFromFile(file5);
    String agoda5 = FilesUtil.getAsStringFromFile(file6);
    //        String agoda6 = FilesUtil.getAsStringFromFile(file7);
    //        String agoda7 = FilesUtil.getAsStringFromFile(file8);
    //        String agoda8 = FilesUtil.getAsStringFromFile(file9);
    //        String agoda9 = FilesUtil.getAsStringFromFile(file10);
    //        String agoda10 = FilesUtil.getAsStringFromFile(file11);
    //        String agoda11 = FilesUtil.getAsStringFromFile(file12);
    //        String agoda12 = FilesUtil.getAsStringFromFile(file13);
    //        String agoda13 = FilesUtil.getAsStringFromFile(file14);
    //        String agoda14 = FilesUtil.getAsStringFromFile(file15);
    //        String agoda15 = FilesUtil.getAsStringFromFile(file16);
    ////        System.out.println(" Test Nya adalah :" + agoda);
    ////        String a=StringUtils.substringAfter("\"HotelTranslatedName\":", agoda);
    ////        System.out.println(" hasil; "+a);
    ////        // TODO code application logic here
    ////        System.out.println("Nilai " + JsonConverter.getValueByKeyStatic(agoda, "HotelTranslatedName"));
    TypeToken<List<HotelModel>> token = new TypeToken<List<HotelModel>>() {
    };
    Gson gson = new GsonBuilder().create();
    //        List<HotelModel> data = new ArrayList<>();
    //        HotelModel hotelModel = new HotelModel();
    //        hotelModel.setAddress("sdfsdffsfsdfsdfdsfdsf");
    //        hotelModel.setAccommodationName("Aku");
    //        HotelModel hotelModel1 = new HotelModel();
    //        hotelModel1.setAddress("sdfsdffsfsdfsdfdsfdsf");
    //        hotelModel1.setAccommodationName("Avvvku");
    //        HotelModel hotelModel2 = new HotelModel();
    //        hotelModel2.setAddress("sdfsdffsfsdfsdfdsfdsf");
    //        hotelModel2.setAccommodationName("Akvvvu");
    //        data.add(hotelModel);
    //        data.add(hotelModel1);
    //        data.add(hotelModel2);
    //        String json = gson.toJson(data);
    List<HotelModel> total = new ArrayList<>();
    List<HotelModel> data1 = new ArrayList<>();
    List<HotelModel> data2 = new ArrayList<>();
    List<HotelModel> data3 = new ArrayList<>();
    List<HotelModel> data4 = new ArrayList<>();
    List<HotelModel> data5 = new ArrayList<>();
    List<HotelModel> data6 = new ArrayList<>();
    List<HotelModel> data7 = new ArrayList<>();
    List<HotelModel> data8 = new ArrayList<>();
    List<HotelModel> data9 = new ArrayList<>();
    List<HotelModel> data10 = new ArrayList<>();
    List<HotelModel> data11 = new ArrayList<>();
    List<HotelModel> data12 = new ArrayList<>();
    List<HotelModel> data13 = new ArrayList<>();
    List<HotelModel> data14 = new ArrayList<>();
    List<HotelModel> data15 = new ArrayList<>();
    List<HotelModel> data16 = new ArrayList<>();

    data1 = gson.fromJson(agoda, token.getType());
    data2 = gson.fromJson(agoda1, token.getType());
    data3 = gson.fromJson(agoda2, token.getType());
    data4 = gson.fromJson(agoda3, token.getType());
    data5 = gson.fromJson(agoda4, token.getType());
    data6 = gson.fromJson(agoda5, token.getType());
    //        data7 = gson.fromJson(agoda6, token.getType());
    //        data8 = gson.fromJson(agoda7, token.getType());
    //        data9 = gson.fromJson(agoda8, token.getType());
    //        data10 = gson.fromJson(agoda9, token.getType());
    //        data11 = gson.fromJson(agoda10, token.getType());
    //        data12 = gson.fromJson(agoda11, token.getType());
    //        data13 = gson.fromJson(agoda12, token.getType());
    //        data14 = gson.fromJson(agoda13, token.getType());
    //        data15 = gson.fromJson(agoda14, token.getType());
    //        data16 = gson.fromJson(agoda15, token.getType());
    total.addAll(data1);
    total.addAll(data2);
    total.addAll(data3);
    total.addAll(data4);
    total.addAll(data5);
    total.addAll(data6);
    //        total.addAll(data7);
    //        total.addAll(data8);
    //        total.addAll(data9);
    //        total.addAll(data10);
    //        total.addAll(data11);
    //        total.addAll(data12);
    //        total.addAll(data13);
    //        total.addAll(data14);
    //        total.addAll(data15);
    //        total.addAll(data16);
    System.out.println(" Ukurannn nya " + total.size());

    //        System.out.println(" Ukurannya " + data2.size());
    for (HotelModel mode : total) {
        System.out.println(mode);
    }
    //        HotelModel hotelModel = gson.fromJson(agoda, HotelModel.class);
    //        String Data = hotelModel.getHotelTranslatedName() + ";" + hotelModel.getStarRating() + ";" + hotelModel.getAddress() + ";" + hotelModel.getIsFreeWifi();
    //        FilesUtil.writeToFileFromString(file2, Data);
    //        System.out.println(hotelModel);
    //
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Agoda Data Hotel Surabaya");

    ////
    TreeMap<String, Object[]> datatoExel = new TreeMap<>();
    int i = 1;
    //        datatoExel.put("1", new Object[]{"Hotel Agoda Jakarta"});
    datatoExel.put("1", new Object[] { "Nama Hotel", "Arena", "Alamat", "Rating", "Apakah Gratis Wifi",
            "Harga Mulai Dari", "Longitude", "Latitude" });
    for (HotelModel mode : total) {
        datatoExel.put(String.valueOf(i + 1),
                new Object[] { mode.getHotelTranslatedName(), mode.getAreaName(), mode.getAddress(),
                        mode.getStarRating(), mode.getIsFreeWifi(),
                        mode.getTextPrice() + " " + mode.getCurrencyCode(), mode.getCoordinate().getLongitude(),
                        mode.getCoordinate().getLatitude() });
        i++;
    }
    //
    ////          int i=1;
    ////        for (HotelModel mode : data2) {
    ////             datatoExel.put(String.valueOf(i), new Object[]{1d, "John", 1500000d});
    //////        }
    ////       
    ////        datatoExel.put("4", new Object[]{3d, "Dean", 700000d});
    ////
    Set<String> keyset = datatoExel.keySet();
    int rownum = 0;
    for (String key : keyset) {
        Row row = sheet.createRow(rownum++);
        Object[] objArr = datatoExel.get(key);
        int cellnum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            if (obj instanceof Date) {
                cell.setCellValue((Date) obj);
            } else if (obj instanceof Boolean) {
                cell.setCellValue((Boolean) obj);
            } else if (obj instanceof String) {
                cell.setCellValue((String) obj);
            } else if (obj instanceof Double) {
                cell.setCellValue((Double) obj);
            }
        }
    }

    try {
        FileOutputStream out = new FileOutputStream(new File("C:\\Users\\deni.fahri\\Documents\\Surabaya.xls"));
        workbook.write(out);
        out.close();
        System.out.println("Excel written successfully..");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.insoul.ti.controller.ContestProjectEntryController.java

@RequestMapping("/download")
public ModelAndView download(HttpServletResponse response) throws Exception {
    HSSFWorkbook workbook = new HSSFWorkbook();// Excel
    HSSFSheet sheet = workbook.createSheet();// ExcelSheet
    sheet.createFreezePane(1, 2);// 
    // /*from w  w w  .  j  av  a 2 s  . c  o m*/
    sheet.setColumnWidth(0, 1000);
    sheet.setColumnWidth(1, 3500);
    sheet.setColumnWidth(2, 3500);
    sheet.setColumnWidth(3, 6500);
    sheet.setColumnWidth(4, 6500);
    sheet.setColumnWidth(5, 6500);
    sheet.setColumnWidth(6, 6500);
    sheet.setColumnWidth(7, 2500);
    // Sheet?
    //        HSSFCellStyle sheetStyle = workbook.createCellStyle();
    // 
    //        sheetStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
    // ?
    //        sheetStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    // ?
    //        sheetStyle.setFillPattern(HSSFCellStyle.FINE_DOTS);
    // ?
    //        for (int i = 0; i <= 14; i++) {
    //            sheet.setDefaultColumnStyle((short) i, sheetStyle);
    //        }
    // 
    HSSFFont headfont = workbook.createFont();
    headfont.setFontName("");
    headfont.setFontHeightInPoints((short) 22);// ?
    headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 
    // ??
    HSSFCellStyle headstyle = workbook.createCellStyle();
    headstyle.setFont(headfont);
    headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// ?
    headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 
    headstyle.setLocked(true);
    headstyle.setWrapText(true);// ?
    // ??
    HSSFFont columnHeadFont = workbook.createFont();
    columnHeadFont.setFontName("");
    columnHeadFont.setFontHeightInPoints((short) 10);
    columnHeadFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    // ?
    HSSFCellStyle columnHeadStyle = workbook.createCellStyle();
    columnHeadStyle.setFont(columnHeadFont);
    columnHeadStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// ?
    columnHeadStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 
    columnHeadStyle.setLocked(true);
    columnHeadStyle.setWrapText(true);
    columnHeadStyle.setLeftBorderColor(HSSFColor.BLACK.index);// 
    columnHeadStyle.setBorderLeft((short) 1);// ?
    columnHeadStyle.setRightBorderColor(HSSFColor.BLACK.index);// ?
    columnHeadStyle.setBorderRight((short) 1);// ?
    columnHeadStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // ?
    columnHeadStyle.setBottomBorderColor(HSSFColor.BLACK.index); // ?
    // ????
    columnHeadStyle.setFillForegroundColor(HSSFColor.WHITE.index);

    HSSFFont font = workbook.createFont();
    font.setFontName("");
    font.setFontHeightInPoints((short) 10);
    // ??
    HSSFCellStyle style = workbook.createCellStyle();
    style.setFont(font);
    style.setAlignment(HSSFCellStyle.ALIGN_LEFT);// ?
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);// 
    style.setWrapText(true);
    style.setLeftBorderColor(HSSFColor.BLACK.index);
    style.setBorderLeft((short) 1);
    style.setRightBorderColor(HSSFColor.BLACK.index);
    style.setBorderRight((short) 1);
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // ?
    style.setBottomBorderColor(HSSFColor.BLACK.index); // ?
    style.setFillForegroundColor(HSSFColor.WHITE.index);// ?
    // ??
    HSSFCellStyle centerstyle = workbook.createCellStyle();
    centerstyle.setFont(font);
    centerstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// ?
    centerstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 
    centerstyle.setWrapText(true);
    centerstyle.setLeftBorderColor(HSSFColor.BLACK.index);
    centerstyle.setBorderLeft((short) 1);
    centerstyle.setRightBorderColor(HSSFColor.BLACK.index);
    centerstyle.setBorderRight((short) 1);
    centerstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // ?
    centerstyle.setBottomBorderColor(HSSFColor.BLACK.index); // ?
    centerstyle.setFillForegroundColor(HSSFColor.WHITE.index);// ?
    try {
        // 
        HSSFRow row0 = sheet.createRow(0);
        // 
        row0.setHeight((short) 900);
        // 
        HSSFCell cell0 = row0.createCell(0);
        cell0.setCellValue(new HSSFRichTextString("???"));
        cell0.setCellStyle(headstyle);
        /**
         * ?? ??0 ??0 ??0 ??0
         */
        CellRangeAddress range = new CellRangeAddress(0, 0, 0, 14);
        sheet.addMergedRegion(range);
        // 
        HSSFRow row1 = sheet.createRow(1);
        row1.setHeight((short) 750);
        HSSFCell cell = row1.createCell(0);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(1);
        cell.setCellValue(new HSSFRichTextString(""));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(2);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(3);
        cell.setCellValue(new HSSFRichTextString(""));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(4);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(5);
        cell.setCellValue(new HSSFRichTextString(""));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(6);
        cell.setCellValue(new HSSFRichTextString("?"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(7);
        cell.setCellValue(new HSSFRichTextString(""));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(8);
        cell.setCellValue(new HSSFRichTextString(""));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(9);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(10);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(11);
        cell.setCellValue(new HSSFRichTextString(""));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(12);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(13);
        cell.setCellValue(new HSSFRichTextString("?"));
        cell.setCellStyle(columnHeadStyle);
        cell = row1.createCell(14);
        cell.setCellValue(new HSSFRichTextString("??"));
        cell.setCellStyle(columnHeadStyle);
        List<ContestEntry> projectList = contestEntryDAO.findAll();
        int m = 2;
        int len = projectList.size();
        for (int i = 0; i < len; i++) {
            ContestEntry c = projectList.get(i);
            HSSFRow row = sheet.createRow(m + i);
            cell = row.createCell(0);
            cell.setCellValue(new HSSFRichTextString(c.getId() + ""));
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue(new HSSFRichTextString(c.getLocation()));
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue(new HSSFRichTextString(c.getInstance()));
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue(new HSSFRichTextString(c.getIndustry()));
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue(new HSSFRichTextString(c.getLegalFormation()));
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue(new HSSFRichTextString(c.getRegtime()));
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue(new HSSFRichTextString(c.getEmployqty() + ""));
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue(new HSSFRichTextString(c.getLegalPerson()));
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue(new HSSFRichTextString(c.getUserCategory()));
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue(new HSSFRichTextString(c.getContact()));
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue(new HSSFRichTextString(c.getIdNumber()));
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue(new HSSFRichTextString(c.getBankName()));
            cell.setCellStyle(style);
            cell = row.createCell(12);
            cell.setCellValue(new HSSFRichTextString(c.getBankUserName()));
            cell.setCellStyle(style);
            cell = row.createCell(13);
            cell.setCellValue(new HSSFRichTextString(c.getBankAccount()));
            cell.setCellStyle(style);
            cell = row.createCell(14);
            cell.setCellValue(new HSSFRichTextString(c.getSupportMoney()));
            cell.setCellStyle(style);
        }
        String filename = System.nanoTime() + ".xls";// Excel??
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
        OutputStream ouputStream = response.getOutputStream();
        workbook.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    } catch (Exception e) {
        log.error("download excel Error.", e);
    }
    return null;
}

From source file:com.isoftstone.web.dao.Car_dao.java

/**
 * ?excel,?excel/*from   www .j  a v  a  2s .c o m*/
 * @param carlist
 * @param path
 * @return ?excel
 */
public boolean addToExcel(List<Car_inf> carlist, String path) {

    System.out.println("excel\n");
    // webbookExcel  
    HSSFWorkbook wb = new HSSFWorkbook();
    // webbooksheet,Excelsheet  
    HSSFSheet sheet = wb.createSheet("");
    // sheet0,poiExcelshort  
    HSSFRow row = sheet.createRow((int) 0);
    //    
    HSSFCellStyle style = wb.createCellStyle();
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //   

    HSSFCell cell = row.createCell((short) 0);
    cell.setCellValue("id");
    cell.setCellStyle(style);
    cell = row.createCell((short) 1);
    cell.setCellValue("");
    cell.setCellStyle(style);
    cell = row.createCell((short) 2);
    cell.setCellValue("");
    cell.setCellStyle(style);
    cell = row.createCell((short) 3);
    cell.setCellValue("");
    cell.setCellStyle(style);
    cell = row.createCell((short) 4);
    cell.setCellValue("");
    cell.setCellStyle(style);
    cell = row.createCell((short) 5);
    cell.setCellValue("");
    cell.setCellStyle(style);

    for (int i = 0; i < carlist.size(); i++) {
        row = sheet.createRow((int) i + 1);
        Car_inf car = (Car_inf) carlist.get(i);
        //   
        String logon = car.getLogon().toString();
        String dated = car.getDated().toString();
        row.createCell((short) 0).setCellValue(car.getId());
        row.createCell((short) 1).setCellValue(car.getBrand());
        row.createCell((short) 2).setCellValue(car.getSeat());
        row.createCell((short) 3).setCellValue(logon);
        row.createCell((short) 4).setCellValue(dated);
        row.createCell((short) 5).setCellValue(car.getD_license());
        row.createCell((short) 6).setCellValue(car.getC_license());
    }
    //   
    try {
        System.out.println("true\n");
        String name = path + "?.xls";
        FileOutputStream fout = new FileOutputStream(name);
        wb.write(fout);
        fout.close();
        System.out.println("\n");
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}

From source file:com.jeecg.controller.giftbook.ApiTruckController.java

/**
 * excel/*  w w w  . ja va2  s  . co  m*/
 * 
 * @param request
 * @param response
 */
@RequestMapping(params = "exportXls")
public void exportXls(TruckEntity truck, HttpServletRequest request, HttpServletResponse response,
        DataGrid dataGrid) {
    response.setContentType("application/vnd.ms-excel");
    String codedFileName = null;
    OutputStream fOut = null;
    try {
        codedFileName = "truck";
        // ??????
        if (BrowserUtils.isIE(request)) {
            response.setHeader("content-disposition",
                    "attachment;filename=" + java.net.URLEncoder.encode(codedFileName, "UTF-8") + ".xls");
        } else {
            String newtitle = new String(codedFileName.getBytes("UTF-8"), "ISO8859-1");
            response.setHeader("content-disposition", "attachment;filename=" + newtitle + ".xls");
        }
        // 
        HSSFWorkbook workbook = null;
        CriteriaQuery cq = new CriteriaQuery(TruckEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, truck,
                request.getParameterMap());

        List<TruckEntity> trucks = this.truckService.getListByCriteriaQuery(cq, false);
        workbook = ExcelExportUtil
                .exportExcel(
                        new ExcelTitle("truck",
                                ":" + ResourceUtil.getSessionUserName().getRealName(), "?"),
                        TruckEntity.class, trucks);
        fOut = response.getOutputStream();
        workbook.write(fOut);
    } catch (Exception e) {
    } finally {
        try {
            fOut.flush();
            fOut.close();
        } catch (IOException e) {

        }
    }
}