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

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

Introduction

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

Prototype

void write(OutputStream stream) throws IOException;

Source Link

Document

Write out this workbook to an Outputstream.

Usage

From source file:com.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   w w w. j  a  v  a2s .  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);
    fileOut.close();/*from  w w  w .  j av  a 2  s .  c  om*/
}

From source file:com.lushapp.common.excel.ExportExcel.java

License:Apache License

private void exportExcelInUserModel(String title, Class<T> pojoClass, Collection<T> dataSet, OutputStream out) {
    try {//w  w w.  j av  a  2 s  .  c o  m
        // ??
        if (dataSet == null || dataSet.size() == 0) {
            throw new Exception("??");
        }
        if (title == null || out == null || pojoClass == null) {
            throw new Exception("???");
        }
        // 
        Workbook workbook = new HSSFWorkbook();
        // ?
        Sheet sheet = workbook.createSheet(title);

        // 
        List<String> exportFieldTitle = new ArrayList<String>();
        List<Integer> exportFieldWidth = new ArrayList<Integer>();
        // ???get
        List<Method> methodObj = new ArrayList<Method>();
        Map<String, Method> convertMethod = new HashMap<String, Method>();
        // 
        Field fileds[] = pojoClass.getDeclaredFields();
        // ??filed
        for (int i = 0; i < fileds.length; i++) {
            Field field = fileds[i];
            Excel excel = field.getAnnotation(Excel.class);
            // annottion
            if (excel != null) {
                // 
                exportFieldTitle.add(excel.exportName());
                // 
                exportFieldWidth.add(excel.exportFieldWidth());
                // ?
                String fieldname = field.getName();
                // System.out.println(i+""+excel.exportName()+" "+excel.exportFieldWidth());
                StringBuffer getMethodName = new StringBuffer("get");
                getMethodName.append(fieldname.substring(0, 1).toUpperCase());
                getMethodName.append(fieldname.substring(1));

                Method getMethod = pojoClass.getMethod(getMethodName.toString(), new Class[] {});

                methodObj.add(getMethod);
                if (excel.exportConvert() == true) {
                    StringBuffer getConvertMethodName = new StringBuffer("get");
                    getConvertMethodName.append(fieldname.substring(0, 1).toUpperCase());
                    getConvertMethodName.append(fieldname.substring(1));
                    getConvertMethodName.append("Convert");
                    Method getConvertMethod = pojoClass.getMethod(getConvertMethodName.toString(),
                            new Class[] {});
                    convertMethod.put(getMethodName.toString(), getConvertMethod);
                }
            }
        }
        int index = 0;
        // 
        Row row = sheet.createRow(index);
        for (int i = 0, exportFieldTitleSize = exportFieldTitle.size(); i < exportFieldTitleSize; i++) {
            Cell cell = row.createCell(i);
            // cell.setCellStyle(style);
            RichTextString text = new HSSFRichTextString(exportFieldTitle.get(i));
            cell.setCellValue(text);
        }

        // ?
        for (int i = 0; i < exportFieldWidth.size(); i++) {
            // 256=65280/255
            sheet.setColumnWidth(i, 256 * exportFieldWidth.get(i));
        }
        Iterator its = dataSet.iterator();
        // ??
        while (its.hasNext()) {
            // 
            index++;
            row = sheet.createRow(index);
            Object t = its.next();
            for (int k = 0, methodObjSize = methodObj.size(); k < methodObjSize; k++) {
                Cell cell = row.createCell(k);
                Method getMethod = methodObj.get(k);
                Object value = null;
                if (convertMethod.containsKey(getMethod.getName())) {
                    Method cm = convertMethod.get(getMethod.getName());
                    value = cm.invoke(t, new Object[] {});
                } else {
                    value = getMethod.invoke(t, new Object[] {});
                }
                cell.setCellValue(value == null ? "" : value.toString());
            }
        }

        workbook.write(out);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.lw.common.utils.ExcelUtil.java

public <T> void returnFailImportExcel(HttpServletResponse response, String modelPath, List<T> objectList,
        Class<T> modelClass, Map<String, String> columnMap) {
    //        result.setData("D:\\lw7068\\Desktop\\ (4)\\??.xlsx");
    //        result.setMessage("shibai",0);
    //        return result;
    OutputStream outputStream = null;
    try {/*from   www  .  j a va 2 s .  c o  m*/
        String fileName = "??" + TimeUtil.currTime();
        Workbook workbook = batchImportFailList(modelPath, objectList, modelClass, columnMap);
        excelName(response, fileName);
        outputStream = response.getOutputStream();
        workbook.write(outputStream);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null)
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

}

From source file:com.lwr.software.reporter.restservices.ReportExportService.java

License:Open Source License

public Response exportExcel(Report toExport, Set<ReportParameter> reportParams) {
    Workbook wb = new XSSFWorkbook();

    Font boldFont = wb.createFont();
    boldFont.setBold(true);/*from w  w  w .j  av a 2s .  c  o m*/

    CellStyle headerStyle = wb.createCellStyle();
    headerStyle.setBorderBottom(BorderStyle.THIN);
    headerStyle.setBorderTop(BorderStyle.THIN);
    headerStyle.setBorderRight(BorderStyle.THIN);
    headerStyle.setBorderLeft(BorderStyle.THIN);
    headerStyle.setFillBackgroundColor(IndexedColors.BLUE.getIndex());
    headerStyle.setFont(boldFont);

    CellStyle cellStyle = wb.createCellStyle();
    cellStyle.setBorderBottom(BorderStyle.THIN);
    cellStyle.setBorderTop(BorderStyle.THIN);
    cellStyle.setBorderRight(BorderStyle.THIN);
    cellStyle.setBorderLeft(BorderStyle.THIN);

    CellStyle titleStyle = wb.createCellStyle();
    titleStyle.setBorderBottom(BorderStyle.THIN);
    titleStyle.setBorderTop(BorderStyle.THIN);
    titleStyle.setBorderRight(BorderStyle.THIN);
    titleStyle.setBorderLeft(BorderStyle.THIN);

    List<RowElement> rows = toExport.getRows();
    int sheetIndex = 0;
    for (RowElement rowElement : rows) {
        List<Element> elements = rowElement.getElements();
        for (Element element : elements) {
            try {
                element.setParams(reportParams);
                element.init();
            } catch (Exception e) {
                logger.error("Unable to init '" + element.getTitle() + "' element of report '"
                        + toExport.getTitle() + "' Error " + e.getMessage(), e);
                return Response.serverError().entity("Unable to init '" + element.getTitle()
                        + "' element of report '" + toExport.getTitle() + "' Error " + e.getMessage()).build();
            }
            String sheetName = element.getTitle().substring(0,
                    element.getTitle().length() > 30 ? 30 : element.getTitle().length()) + (sheetIndex++);
            Sheet sheet = wb.createSheet(sheetName);

            Row reportTitleRow = sheet.createRow(0);
            Cell reportTitleHeader = reportTitleRow.createCell(0);
            reportTitleHeader.setCellStyle(headerStyle);
            reportTitleHeader.setCellValue("Report Title:");

            Cell reportTitleCell = reportTitleRow.createCell(1);
            reportTitleCell.setCellStyle(titleStyle);
            reportTitleCell.setCellValue(toExport.getTitle());

            Row elementTitleRow = sheet.createRow(1);
            Cell elementTitleHeader = elementTitleRow.createCell(0);
            elementTitleHeader.setCellStyle(headerStyle);
            elementTitleHeader.setCellValue("Element Title:");

            Cell elementTitleCell = elementTitleRow.createCell(1);
            elementTitleCell.setCellStyle(titleStyle);
            elementTitleCell.setCellValue(element.getTitle());

            List<List<Object>> dataToExport = element.getData();

            int rowIndex = 3;
            Row headerRow = sheet.createRow(rowIndex++);
            List<Object> unifiedHeaderRow = element.getHeader();
            for (int i = 0; i < unifiedHeaderRow.size(); i++) {
                Cell headerCell = headerRow.createCell(i);
                String headerCellValue = unifiedHeaderRow.get(i).toString();
                headerCell.setCellValue(headerCellValue);
                headerCell.setCellStyle(headerStyle);
            }
            for (int i = 0; i < dataToExport.size(); i++) {
                Row row = sheet.createRow(rowIndex++);
                List<Object> unifiedRow = dataToExport.get(i);
                int cellIndex = 0;
                for (Object cellValue : unifiedRow) {
                    Cell cell = row.createCell(cellIndex);
                    cell.setCellStyle(cellStyle);
                    try {
                        double val = Double.parseDouble(cellValue.toString());
                        cell.setCellValue(val);
                    } catch (NumberFormatException e) {
                        cell.setCellValue(cellValue.toString());
                    }
                    cellIndex++;
                }
            }
        }
    }
    try {
        File file = new File(DashboardConstants.APPLN_TEMP_DIR + System.nanoTime());
        logger.info("Export CSV temp file path is " + file.getAbsoluteFile());
        wb.write(new FileOutputStream(file));
        wb.close();
        ResponseBuilder responseBuilder = Response.ok((Object) file);
        responseBuilder.header("Content-Type",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        responseBuilder.header("Content-Transfer-Encoding", "binary");
        responseBuilder.header("Content-Disposition", "attachment;filename=" + file.getName());
        responseBuilder.header("Content-Length", file.length());
        Response responseToSend = responseBuilder.build();
        file.deleteOnExit();
        return responseToSend;
    } catch (Exception e1) {
        return Response.serverError()
                .entity("Unable to export " + toExport.getTitle() + " report " + e1.getMessage()).build();
    }

}

From source file:com.maogousoft.wuliu.controller.DriverController.java

public void exportExcel() throws IOException {
    StringBuffer from = new StringBuffer();
    from.append("from logistics_driver where status = 1 ");
    from.append(createOrder());/*from   w  w  w .jav a  2 s .c o m*/
    Page<Record> page = Db.paginate(getPageIndex(), 100000, "select * ", from.toString());
    List<Record> list = page.getList();
    Dict.fillDictToRecords(page.getList());

    String headers = "?|?|??|??|?|??|||?|??||?|??|?|??|?";
    String attributes = "id|phone|name|recommender|plate_number|id_card|car_type_str|car_length|car_weight|gold|regist_time|car_phone|start_province_str|start_city_str|end_province_str|end_city_str";

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet();
    Row headerRow = sheet.createRow(0);
    List<String> headerList = WuliuStringUtils.parseVertical(headers);
    for (int j = 0; j < headerList.size(); j++) {
        String attr = headerList.get(j);
        Cell cell = headerRow.createCell(j);
        cell.setCellValue(attr);
    }

    for (int i = 0; i < list.size(); i++) {
        Record record = list.get(i);
        Row row = sheet.createRow(i + 1);

        List<String> attrList = WuliuStringUtils.parseVertical(attributes);
        for (int j = 0; j < attrList.size(); j++) {
            String attr = attrList.get(j);
            Cell cell = row.createCell(j);
            Object value = getValue(record, attr);
            cell.setCellValue(value + "");
        }
    }

    HttpServletResponse resp = getResponse();
    String filename = TimeUtil.format(new Date(), "'?'yyyyMMdd_HHmmss'.xls'");
    resp.addHeader("Content-Disposition",
            "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO-8859-1"));
    ServletOutputStream out = resp.getOutputStream();
    wb.write(out);
    out.close();
    renderNull();
}

From source file:com.maogousoft.wuliu.controller.DriverController.java

/**
 * // w w w  .  j a va  2  s.c om
 * @description ? 
 * @author shevliu
 * @email shevliu@gmail.com
 * 201386 ?11:47:19
 * @throws IOException
 */
public void exportPendingAudit() throws IOException {
    StringBuffer from = new StringBuffer();
    from.append("from logistics_driver where status = 0 ");
    from.append(createOrder());
    Page<Record> page = Db.paginate(getPageIndex(), 100000, "select * ", from.toString());
    List<Record> list = page.getList();
    Dict.fillDictToRecords(page.getList());

    String headers = "?|?|??|??|?|??|||?|??||?|??|?|??|?";
    String attributes = "id|phone|name|recommender|plate_number|id_card|car_type_str|car_length|car_weight|gold|regist_time|car_phone|start_province_str|start_city_str|end_province_str|end_city_str";

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet();
    Row headerRow = sheet.createRow(0);
    List<String> headerList = WuliuStringUtils.parseVertical(headers);
    for (int j = 0; j < headerList.size(); j++) {
        String attr = headerList.get(j);
        Cell cell = headerRow.createCell(j);
        cell.setCellValue(attr);
    }

    for (int i = 0; i < list.size(); i++) {
        Record record = list.get(i);
        Row row = sheet.createRow(i + 1);
        List<String> attrList = WuliuStringUtils.parseVertical(attributes);
        for (int j = 0; j < attrList.size(); j++) {
            String attr = attrList.get(j);
            Cell cell = row.createCell(j);
            Object value = getValue(record, attr);
            cell.setCellValue(value + "");
        }
    }

    HttpServletResponse resp = getResponse();
    String filename = TimeUtil.format(new Date(), "'?'yyyyMMdd_HHmmss'.xls'");
    resp.addHeader("Content-Disposition",
            "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO-8859-1"));
    ServletOutputStream out = resp.getOutputStream();
    wb.write(out);
    out.close();
    renderNull();
}

From source file:com.md.mdcms.xlsx.CSVtoXLSX.java

License:Open Source License

/**
 * @param args//from  www. j  a  v a2  s  .co  m
 */
public static void main(String[] args) {
    // check if correct number of arguments were passed
    if (args.length != 23) {
        System.out.println("Invalid number of Parameters passed");
        System.out.println("Parameters expected = 23");
        System.out.println("Parameters passed = " + args.length);
        System.out.println("Expected parameters: ");
        System.out.println("1) csv file path");
        System.out.println("2) excel file path");
        System.out.println("3) Header1");
        System.out.println("4) Header2");
        System.out.println("5) Header3");
        System.out.println("6) Header4");
        System.out.println("7) Header5");
        System.out.println("8) Header6");
        System.out.println("9) Header7");
        System.out.println("10) Header8");
        System.out.println("11) Header9");
        System.out.println("12) Footer1");
        System.out.println("13) Footer2");
        System.out.println("14) Footer3");
        System.out.println("15) Footer4");
        System.out.println("16) Footer5");
        System.out.println("17) Footer6");
        System.out.println("18) Field Types1");
        System.out.println("19) Field Types2");
        System.out.println("20) Field Types3");
        System.out.println("21) Field Types4");
        System.out.println("22) Date order");
        System.out.println("23) Date Separator");
        System.exit(1);
    }

    try {
        System.setProperty("java.awt.headless", "true");
        File csvFile = new File(args[0]);
        File xlsFile = new File(args[1]);
        String dateOrder = args[21];
        String dateSep = args[22];

        // prep CSV
        String lineIn;
        BufferedReader br = new BufferedReader(new FileReader(csvFile));

        // Workbook Settings
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Sheet1");

        //         wb.setLocale(new Locale("en", "EN"));
        //         WritableWorkbook workbook = Workbook.createWorkbook(xlsFile, ws);
        //         WritableSheet sheet = workbook.createSheet("Table1", 0);
        //         SheetSettings settings = new SheetSettings(sheet);
        //         settings.setFitToPages(true);
        //         settings.setPaperSize(PaperSize.A4);
        //         settings.setOrientation(PageOrientation.LANDSCAPE);

        // set cell formats         
        //         arial9Format.setShrinkToFit(true);
        //         arial9Format.setWrap(true);
        //         arial9TotalIntegerFormat.setShrinkToFit(true);
        //         arial9TotalIntegerFormat.setBorder(Border.TOP, BorderLineStyle.DOUBLE);
        //         arial9TotalFloatFormat.setShrinkToFit(true);
        //         arial9TotalFloatFormat.setBorder(Border.TOP, BorderLineStyle.DOUBLE);
        //         colHeaderFormat.setBackground(Colour.GREY_25_PERCENT);
        //         colHeaderFormat.setWrap(true);
        //         colHeaderFormat.setShrinkToFit(true);
        //         colHeaderFormat.setVerticalAlignment(VerticalAlignment.TOP);
        //         floatFormat.setShrinkToFit(true);
        //         floatFormat.setWrap(true);
        //         integerFormat.setShrinkToFit(true);
        //         integerFormat.setWrap(true);
        //         headerFormat.setBackground(Colour.GREY_25_PERCENT);
        //         headerFormat.setShrinkToFit(true);
        //         footerFormat.setBackground(Colour.GREY_25_PERCENT);
        //         footerFormat.setShrinkToFit(true);

        // cell(column, row)
        int colnr = 0;
        int rownr = 0;
        int firstHeaderRow = 0;

        // Headers
        String[] header = { args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10] };
        int lastHeaderRow = firstHeaderRow;
        boolean headerFound = false;
        for (int j = 8; j > -1; j--) {
            if (!"".equals(header[j].trim()) || (headerFound)) {
                Label label = new Label(0, j + firstHeaderRow, header[j].replaceAll("\\s+$", ""), headerFormat);
                sheet.addCell(label);
                if (!headerFound) {
                    headerFound = true;
                    lastHeaderRow = j + firstHeaderRow;
                }
            }
        }

        // fill field type list
        String fieldTypes = args[17].trim() + args[18].trim() + args[19].trim() + args[20].trim();
        String[] fieldType = fieldTypes.split(",");

        // table data
        int columnHeadingRow = lastHeaderRow;
        if (headerFound) {
            columnHeadingRow += 2;
        }
        rownr = columnHeadingRow;
        int firstDataRow = 0;
        int lastDataRow = 0;
        String[] char13 = { "m", "w", "A", "B", "C", "D", "E", "G", "H", "K", "M", "N", "O", "P", "Q", "R", "S",
                "U", "V", "W" };
        double factor = 1.0;
        int width;
        double w;
        double charWidth;
        String value;

        // loop through CSV lines
        lineIn = br.readLine();
        while (lineIn != null && !"".equals(lineIn)) {
            String[] fields = lineIn.split("\t");

            // loop through columns in line
            for (int i = 0; (i < fields.length && i < fieldType.length); i++) {
                if (!fieldType[i].substring(0, 1).equals("E")) {
                    value = fields[i];
                    value = value.replaceAll("\"", "").trim();

                    // column heading
                    if (rownr == columnHeadingRow) {
                        factor = 1.3;
                        Label label = new Label(colnr, rownr, value, colHeaderFormat);
                        sheet.addCell(label);
                    }

                    // column data
                    else {
                        factor = 1;
                        if (firstDataRow == 0) {
                            firstDataRow = rownr;
                        }
                        lastDataRow = rownr;

                        // date field
                        if (fieldType[i].equals("D")) {
                            if (value.length() == 6) {
                                if (dateOrder.equals("DMY")) {
                                    value = value.substring(4, 6) + dateSep + value.substring(2, 4) + dateSep
                                            + value.substring(0, 2);
                                } else {
                                    if (dateOrder.equals("MDY")) {
                                        value = value.substring(2, 4) + dateSep + value.substring(4, 6)
                                                + dateSep + value.substring(0, 2);
                                    } else {
                                        value = value.substring(0, 2) + dateSep + value.substring(2, 4)
                                                + dateSep + value.substring(4, 6);
                                    }
                                }
                            }
                            if (value.length() == 8) {
                                if (dateOrder.equals("DMY")) {
                                    value = value.substring(6, 8) + dateSep + value.substring(4, 6) + dateSep
                                            + value.substring(0, 4);
                                } else {
                                    if (dateOrder.equals("MDY")) {
                                        value = value.substring(2, 4) + dateSep + value.substring(4, 6)
                                                + dateSep + value.substring(0, 4);
                                    } else {
                                        value = value.substring(0, 4) + dateSep + value.substring(4, 6)
                                                + dateSep + value.substring(6, 8);
                                    }
                                }
                            }
                            Label label = new Label(colnr, rownr, value, arial9Format);
                            sheet.addCell(label);
                        }

                        // floating point field
                        if (fieldType[i].substring(0, 1).equals("F")) {
                            try {
                                double doubleValue = Double.valueOf(value).doubleValue();
                                Number number = new Number(colnr, rownr, doubleValue, floatFormat);
                                sheet.addCell(number);
                            } catch (Exception e) {
                                Label label = new Label(colnr, rownr, value, arial9Format);
                                sheet.addCell(label);
                            }
                        }

                        // integer field
                        if (fieldType[i].substring(0, 1).equals("I")) {
                            try {
                                int integerValue = Integer.valueOf(value).intValue();
                                Number number = new Number(colnr, rownr, integerValue, integerFormat);
                                sheet.addCell(number);
                            } catch (Exception e) {
                                Label label = new Label(colnr, rownr, value, arial9Format);
                                sheet.addCell(label);
                            }
                        }

                        // string field
                        if (fieldType[i].equals("S")) {
                            Label label = new Label(colnr, rownr, value, arial9Format);
                            sheet.addCell(label);
                        }
                    }

                    //      calculate cell width and add column number
                    w = 1;
                    for (int j = 0; j < value.length(); j++) {
                        charWidth = 1;
                        for (int k = 0; k < char13.length; k++) {
                            if (char13[k].equals(value.substring(j, j + 1))) {
                                charWidth = 1.3;
                                k = char13.length;
                            }
                        }
                        w = w + (charWidth * factor);
                    }
                    width = Double.valueOf(String.valueOf(w)).intValue();
                    if (width > 80) {
                        width = 80;
                    }
                    concludeColumnWidth(colnr, width);
                    colnr++;
                }
            }
            lineIn = br.readLine();
            colnr = 0;
            rownr++;
        }

        for (Iterator iterator = columnWidth.keySet().iterator(); iterator.hasNext();) {
            Integer col = (Integer) iterator.next();
            sheet.setColumnView(col.intValue(), ((Integer) columnWidth.get(col)).intValue());
        }

        // total row
        colnr = 0;
        int columnCount = 5;
        for (int i = 0; i < fieldType.length; i++) {
            if (!fieldType[i].substring(0, 1).equals("E")) {
                if (fieldType[i].length() > 1) {
                    if (fieldType[i].substring(1, 2).equals("T")) {
                        String firstCell;
                        String lastCell;
                        firstCell = CellReferenceHelper.getCellReference(colnr, firstDataRow);
                        lastCell = CellReferenceHelper.getCellReference(colnr, lastDataRow);
                        value = "SUM(" + firstCell + ":" + lastCell + ")";
                        if (fieldType[i].substring(0, 1).equals("F")) {
                            Formula formula = new Formula(colnr, rownr, value, arial9TotalFloatFormat);
                            sheet.addCell(formula);
                        } else {
                            Formula formula = new Formula(colnr, rownr, value, arial9TotalIntegerFormat);
                            sheet.addCell(formula);
                        }
                    }
                }
                colnr++;
                if (colnr > columnCount) {
                    columnCount = colnr;
                }
            }
        }

        // merge the header cells
        if (headerFound) {
            for (int i = firstHeaderRow; i <= lastHeaderRow; i++) {
                sheet.mergeCells(0, i, columnCount - 1, i);
            }
        }

        // Footers
        String[] footer = { args[11], args[12], args[13], args[14], args[15], args[16] };
        boolean footerFound = false;
        rownr++;
        for (int j = 5; j > -1; j--) {
            if (!"".equals(footer[j].trim()) || (footerFound)) {
                Label label = new Label(0, rownr + j, footer[j].replaceAll("\\s+$", ""), footerFormat);
                sheet.addCell(label);
                sheet.mergeCells(0, rownr + j, columnCount - 1, rownr + j);
                footerFound = true;
            }
        }

        // write workbook to file
        if (xlsFile.exists()) {
            xlsFile.delete();
        }
        FileOutputStream fileOut = new FileOutputStream(xlsFile);
        wb.write(fileOut);
        fileOut.close();

    } catch (UnsupportedEncodingException e) {
        System.out.println(e.toString());
        System.exit(1);
    } catch (IOException e) {
        System.out.println(e.toString());
        System.exit(1);
    } catch (Exception e) {
        System.out.println(e.toString());
        System.exit(1);
    }
}

From source file:com.mechatronika.trackmchtr.ExportToExcel.java

private static void writeToExcel(String path) throws FileNotFoundException, IOException {
    new WorkbookFactory();
    Workbook wb = new XSSFWorkbook(); //Excell workbook
    Sheet sheet = wb.createSheet(); //WorkSheet //wb.createSheet("sheetName");
    Row row = sheet.createRow(2); //Row created at line 3
    TableModel model = table.getModel(); //Table model

    Row headerRow = sheet.createRow(0); //Create row at line 0
    for (int headings = 0; headings < model.getColumnCount(); headings++) { //For each column
        headerRow.createCell(headings).setCellValue(model.getColumnName(headings));//Write column name
    }//from  w  ww  .j  av a 2 s.  c  o m

    for (int rows = 0; rows < model.getRowCount(); rows++) { //For each table row
        for (int cols = 0; cols < table.getColumnCount(); cols++) { //For each table column
            row.createCell(cols).setCellValue(model.getValueAt(rows, cols).toString()); //Write value
        }

        //Set the row to the next one in the sequence 
        row = sheet.createRow((rows + 3));
    }
    wb.write(new FileOutputStream(path));//Save the file  
    IJ.showMessage("Excel file created!");
}

From source file:com.mimp.controllers.reporte.java

@RequestMapping("/Reportes/OrganismosAcreditados")
    public void ReporteOrganismo(ModelMap map, HttpSession session, HttpServletResponse response) {
        Personal usuario = (Personal) session.getAttribute("usuario");
        Workbook wb = new XSSFWorkbook();
        try {//from  ww w.  java 2s.com
            //Se llama a la plantilla localizada en la ruta

            //            InputStream inp = new FileInputStream("C:\\Plantillas\\OrgAcred.xlsx");
            InputStream inp = new FileInputStream("/opt/Plantillas/OrgAcred.xlsx");

            wb = WorkbookFactory.create(inp);
            Sheet sheet = wb.getSheetAt(0);

            //Aqu va el query que consigue los datos de la tabla
            //ArrayList<Organismo> listaorg = ServicioPersonal.ListaOrganismos();
            ArrayList<Organismo> listaorg = ServicioReporte.ReporteOrganismo2();

            int i = 1;
            for (Organismo org : listaorg) {
                Row row = sheet.createRow(i);

                Cell cell = row.createCell(0);
                cell.setCellValue(i);
                cell = row.createCell(1);
                cell.setCellValue(org.getEntidad().getNombre());
                cell = row.createCell(2);
                cell.setCellValue(org.getCompetencia());
                cell = row.createCell(3);
                cell.setCellValue(org.getEntidad().getResolAuto());
                cell = row.createCell(4);
                String fechaVenc = "";
                try {
                    fechaVenc = format.dateToString(org.getEntidad().getFechaVenc());
                } catch (Exception ex) {
                }
                cell.setCellValue(fechaVenc);
                cell = row.createCell(5);
                for (Iterator iter = org.getRepresentantes().iterator(); iter.hasNext();) {
                    Representante rep = (Representante) iter.next();
                    cell.setCellValue(rep.getNombre() + " " + rep.getApellidoP());
                }
                cell = row.createCell(6);
                cell.setCellValue(org.getEntidad().getObs());

                i++;
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition",
                    "attachment; filename=Registro del nmero Organismos Acreditados.xlsx");
            OutputStream fileOut = response.getOutputStream();
            wb.write(fileOut);
            fileOut.flush();
            fileOut.close();
        } catch (Exception ex) {
            //ex.printStackTrace();
        }

        String mensaje_log = "El usuario: " + usuario.getNombre() + " " + usuario.getApellidoP() + " con ID: "
                + usuario.getIdpersonal() + ". Descarg el Reporte 'Organismos Acreditados' ";

        String Tipo_registro = "Personal";

        try {
            String Numero_registro = String.valueOf(usuario.getIdpersonal());

            ServicioPersonal.InsertLog(usuario, Tipo_registro, Numero_registro, mensaje_log);
        } catch (Exception ex) {
        }
    }