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

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

Introduction

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

Prototype

@Override
public XSSFSheet createSheet(String sheetname) 

Source Link

Document

Create a new sheet for this Workbook and return the high level representation.

Usage

From source file:DSC.NewClientReport.java

private static void createExcelReport() {

    XSSFWorkbook workbook = new XSSFWorkbook();
    clients.sort(new Comparator<Client>() {
        @Override/* w  ww . ja  v a 2 s  . co  m*/
        public int compare(Client o1, Client o2) {
            return (o1.getSurname() + " " + o1.getName()).compareTo(o2.getSurname() + " " + o2.getName());
        }
    });

    XSSFSheet sheet = workbook.createSheet("NewClient Report");

    Map<String, Object[]> data = new TreeMap<>();
    data.put("1", new Object[] { "Doorstep Chef NewClient Sheet", "", "",
            "Week: " + DriverReport.returnWeekInt(), "" });
    data.put("2", new Object[] { "", "", "", "", "" });
    data.put("3", new Object[] { "Customer", "Contact", "DriverName", "R.ID", "Email", "Address" });

    int counter = 4;
    for (Client client : clients) {
        data.put(counter + "", new Object[] { client.getName() + " " + client.getSurname(),
                client.getContactNumber().substring(0, 3) + " " + client.getContactNumber().substring(3, 6)
                        + " " + client.getContactNumber().substring(6, 10),
                client.getAdditionalInfo(), client.getAlternativeNumber(), client.getEmail(),
                client.getAddress() });
        counter++;
    }

    Set<String> keySet = data.keySet();
    int totalSize = 34900;
    int longestCustomer = 0;

    for (int key = 1; key < keySet.size() + 1; key++) {
        Row row = sheet.createRow(key - 1);
        Object[] arr = data.get(key + "");
        for (int i = 0; i < arr.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue((String) arr[i]);

            if (i == 0 && !(key + "").equals("1") && longestCustomer < ((String) arr[i]).length()) {
                longestCustomer = ((String) arr[i]).length();
            }
            XSSFCellStyle borderStyle = workbook.createCellStyle();

            if (!((key + "").equals("1") || (key + "").equals("2"))) {
                borderStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
                borderStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
                borderStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
                borderStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
                if ((key + "").equals("3")) {
                    borderStyle.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
                    borderStyle.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
                    borderStyle.setBorderTop(XSSFCellStyle.BORDER_MEDIUM);
                    borderStyle.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
                    borderStyle.setAlignment(HorizontalAlignment.CENTER);
                    borderStyle.setFillPattern(XSSFCellStyle.LESS_DOTS);
                    borderStyle.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
                    XSSFFont font = workbook.createFont();
                    font.setColor(IndexedColors.WHITE.getIndex());
                    font.setBold(true);
                    borderStyle.setFont(font);
                } else {
                    if (i != 0) {
                        borderStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
                    } else {
                        borderStyle.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
                    }
                    if (i != 4) {
                        borderStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
                    } else {
                        borderStyle.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
                    }

                    if ((Integer.parseInt((key + ""))) != keySet.size()) {
                        borderStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
                    } else {
                        borderStyle.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
                    }
                    borderStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);

                }
            } else {
                if (i == 3) {
                    borderStyle.setAlignment(HorizontalAlignment.RIGHT);
                }
                XSSFFont font = workbook.createFont();
                font.setFontName("Calibri");
                font.setFontHeightInPoints((short) 13);
                font.setBold(true);
                borderStyle.setFont(font);
            }

            cell.setCellStyle(borderStyle);

        }
    }

    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
    sheet.addMergedRegion(new CellRangeAddress(0, 0, 3, 5));

    sheet.setColumnWidth(0, (longestCustomer + 2) * 240);
    sheet.setColumnWidth(1, 13 * 240);
    sheet.setColumnWidth(2, 11 * 240);
    sheet.setColumnWidth(3, 5 * 240);

    for (int i = 0; i < 4; i++) {
        totalSize -= sheet.getColumnWidth(i);
    }
    sheet.setColumnWidth(4, totalSize / 2);
    sheet.setColumnWidth(5, totalSize / 2);

    Row rowDate = sheet.createRow(keySet.size() + 1);
    Cell cell = rowDate.createCell(0);
    SimpleDateFormat sf = new SimpleDateFormat("EEE MMM yyyy HH:mm:ss");

    cell.setCellValue(sf.format(Calendar.getInstance().getTime()));
    XSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setAlignment(XSSFCellStyle.ALIGN_RIGHT);
    cell.setCellStyle(cellStyle);
    sheet.addMergedRegion(new CellRangeAddress(keySet.size() + 1, keySet.size() + 1, 0, 5));

    try {
        workbook.write(excelOut);
        excelOut.close();
        System.out.println("Done - New Client");
        if (!(DSC_Main.generateAllReports)) {
            newClientLoadObj.setVisible(false);
            newClientLoadObj.dispose();
            JOptionPane.showMessageDialog(null, "NewClientReports Succesfully Generated", "Success",
                    JOptionPane.INFORMATION_MESSAGE);
        } else {
            DSC_Main.reportsDone++;
            if (DSC_Main.reportsDone == 5) {
                DSC_Main.reportsDone();
            }
        }

    } catch (IOException io) {
        newClientLoadObj.setVisible(false);
        newClientLoadObj.dispose();
        JOptionPane.showMessageDialog(null, "An error occured\nCould not create NewClientReports", "Error",
                JOptionPane.ERROR_MESSAGE);
        System.err.println("Error - Could not create new NewClientReports: ");
        io.printStackTrace();
    }

}

From source file:DSC.PackerReport.java

private static void createSpreadsheets() {
    orderList.sort(new Comparator<Order>() {
        @Override//from   w  w  w  . j a  va 2s  . com
        public int compare(Order o1, Order o2) {
            int result;
            if (o1.getFamilySize() < o2.getFamilySize()) {
                result = -1;
            } else if (o1.getFamilySize() == o2.getFamilySize()) {
                result = 0;
            } else {
                result = 1;
            }
            return result;
        }
    });

    XSSFWorkbook workbook = new XSSFWorkbook();
    for (Route route : routeList) {
        XSSFSheet sheet = workbook.createSheet("PackerReports Route - " + route.getID());

        Map<String, String[]> data = new TreeMap<>();
        data.put("1",
                new String[] { "Doorstep Chef Packer Sheet", "", "",
                        route.getDrivers().get(0).getDriver().getDriverName().split(" ")[0] + " - "
                                + route.getDrivers().get(0).getDriver().getContactNumber(),
                        "", " Week: " + DriverReport.returnWeekInt() + " Route: " + route.getID() });
        data.put("2", new String[] { "", "", "", "", "", "" });
        data.put("3", new String[] { "Customer", "FamSize", "MealType", "Qty", "Allergies", "Exclutions" });

        int[] totals = new int[11];

        int counter = 4;
        for (Order order : orderList) {
            if (order.getRoute().equals(route.getID())) {

                Client client = order.getClient();
                String customer = client.getName() + " " + client.getSurname();
                String famSize = order.getFamilySize() + "";
                for (Meal meal : order.getMeals()) {
                    data.put(counter + "", new String[] { customer, famSize, meal.getMealType(),
                            meal.getQuantity() + "", meal.getAllergies(), meal.getExclusions() });
                    customer = "";
                    famSize = "";
                    counter++;
                    if (meal.getMealType().equals("Standard")) {
                        totals[1] += meal.getQuantity();
                    } else if (meal.getMealType().equals("Low Carb")) {
                        totals[2] += meal.getQuantity();
                    } else if (meal.getMealType().equals("Kiddies")) {
                        totals[3] += meal.getQuantity();
                    }

                    switch (meal.getQuantity()) {
                    case 1:
                        totals[4]++;
                        break;
                    case 2:
                        totals[5]++;
                        break;
                    case 3:
                        totals[6]++;
                        break;
                    case 4:
                        totals[7]++;
                        break;
                    case 5:
                        totals[8]++;
                        break;
                    case 6:
                        totals[9]++;
                        break;
                    default:
                        if (meal.getQuantity() > 6) {
                            totals[10]++;
                        }
                    }
                }
                totals[0]++;
            }
        }

        Set<String> keySet = data.keySet();
        int totalSize = 22000;
        int longestCustomer = 0;
        for (int key = 1; key < keySet.size() + 1; key++) {
            Row row = sheet.createRow(key - 1);
            String[] arr = data.get(key + "");

            for (int i = 0; i < arr.length; i++) {
                Cell cell = row.createCell(i);
                cell.setCellValue(arr[i]);
                XSSFCellStyle borderStyle = workbook.createCellStyle();

                if (i == 0 && !(key + "").equals("1") && longestCustomer < ((String) arr[i]).length()) {
                    longestCustomer = ((String) arr[i]).length();
                }

                if (!((key + "").equals("1") || (key + "").equals("2"))) {
                    borderStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
                    borderStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
                    borderStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
                    borderStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
                    if ((key + "").equals("3")) {
                        borderStyle.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
                        borderStyle.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
                        borderStyle.setBorderTop(XSSFCellStyle.BORDER_MEDIUM);
                        borderStyle.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
                        borderStyle.setAlignment(HorizontalAlignment.CENTER);
                        borderStyle.setFillPattern(XSSFCellStyle.LESS_DOTS);
                        borderStyle.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
                        XSSFFont font = workbook.createFont();
                        font.setColor(IndexedColors.WHITE.getIndex());
                        font.setBold(true);
                        borderStyle.setFont(font);

                    } else {
                        if (i != 0) {
                            borderStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
                        } else {
                            borderStyle.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
                        }
                        if (i != 5) {
                            borderStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
                        } else {
                            borderStyle.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
                        }

                        if (i == 5 || i == 4) {
                            borderStyle.setAlignment(XSSFCellStyle.ALIGN_JUSTIFY);
                            borderStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_JUSTIFY);
                        }

                        if ((Integer.parseInt((key + ""))) != keySet.size()) {
                            borderStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
                        } else {
                            borderStyle.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
                        }
                        borderStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);

                    }
                    if (i == 3 || i == 1) {
                        borderStyle.setAlignment(HorizontalAlignment.CENTER);
                    }
                } else {
                    if (key != 3 && (i == 4 || i == 5)) {
                        borderStyle.setAlignment(XSSFCellStyle.ALIGN_JUSTIFY);
                        borderStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_JUSTIFY);
                    }
                    if (i == 3) {
                        borderStyle.setAlignment(HorizontalAlignment.CENTER);
                    } else if (i == 5) {
                        borderStyle.setAlignment(HorizontalAlignment.RIGHT);
                    }
                    XSSFFont font = workbook.createFont();
                    font.setFontName("Calibri");
                    font.setFontHeightInPoints((short) 13);
                    font.setBold(true);
                    borderStyle.setFont(font);
                }

                cell.setCellStyle(borderStyle);
            }
        }

        //<editor-fold defaultstate="collapsed" desc="Add Totals">
        Row row = sheet.createRow(keySet.size());
        Cell cell1 = row.createCell(0);
        cell1.setCellValue("Clients: " + totals[0]);
        XSSFCellStyle cellStyle1 = workbook.createCellStyle();
        XSSFFont font = workbook.createFont();
        font.setBold(true);
        cellStyle1.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
        cellStyle1.setFont(font);
        cell1.setCellStyle(cellStyle1);

        Cell cell2 = row.createCell(1);
        cell2.setCellValue("Standard: " + totals[1]);
        XSSFCellStyle cellStyle2 = workbook.createCellStyle();
        font.setBold(true);
        cellStyle2.setFont(font);
        cell2.setCellStyle(cellStyle2);

        Cell cell3 = row.createCell(4);
        cell3.setCellValue("Low Carb:  " + totals[2]);
        XSSFCellStyle cellStyle3 = workbook.createCellStyle();
        font.setBold(true);
        cellStyle3.setFont(font);
        cell3.setCellStyle(cellStyle3);

        Cell cell4 = row.createCell(5);
        cell4.setCellValue("Kiddies: " + totals[3]);
        XSSFCellStyle cellStyle4 = workbook.createCellStyle();
        font.setBold(true);
        cellStyle4.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
        cellStyle4.setFont(font);
        cell4.setCellStyle(cellStyle4);

        row = sheet.createRow(keySet.size() + 1);

        Cell holder = row.createCell(0);
        XSSFCellStyle border1 = workbook.createCellStyle();
        border1.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
        holder.setCellStyle(border1);

        cell2 = row.createCell(1);
        cell2.setCellValue("Single: " + totals[4]);
        XSSFCellStyle cellStyle6 = workbook.createCellStyle();
        font.setBold(true);
        cellStyle6.setFont(font);
        cell2.setCellStyle(cellStyle6);

        cell3 = row.createCell(4);
        cell3.setCellValue("Couple:  " + totals[5]);
        XSSFCellStyle cellStyle7 = workbook.createCellStyle();
        font.setBold(true);
        cellStyle7.setFont(font);
        cell3.setCellStyle(cellStyle7);

        cell4 = row.createCell(5);
        cell4.setCellValue("Small(3): " + totals[6]);
        XSSFCellStyle cellStyle8 = workbook.createCellStyle();
        font.setBold(true);
        cellStyle8.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
        cellStyle8.setFont(font);
        cell4.setCellStyle(cellStyle8);

        row = sheet.createRow(keySet.size() + 2);

        Cell holder2 = row.createCell(0);
        XSSFCellStyle border2 = workbook.createCellStyle();
        border2.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
        border2.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
        holder2.setCellStyle(border2);

        cell2 = row.createCell(1);
        cell2.setCellValue("Medium(4): " + totals[7]);
        XSSFCellStyle cellStyle9 = workbook.createCellStyle();
        font.setBold(true);
        cellStyle9.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
        cellStyle9.setFont(font);
        cell2.setCellStyle(cellStyle9);

        Cell holder3 = row.createCell(2);
        XSSFCellStyle border3 = workbook.createCellStyle();
        border3.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
        holder3.setCellStyle(border3);

        Cell holder4 = row.createCell(3);
        XSSFCellStyle border4 = workbook.createCellStyle();
        border4.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
        holder4.setCellStyle(border4);

        cell3 = row.createCell(4);
        cell3.setCellValue("Large(5):  " + totals[8]);
        XSSFCellStyle cellStyle10 = workbook.createCellStyle();
        font.setBold(true);
        cellStyle10.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
        cellStyle10.setFont(font);
        cell3.setCellStyle(cellStyle10);

        cell4 = row.createCell(5);
        cell4.setCellValue("XLarge(6): " + totals[9]);
        XSSFCellStyle cellStyle11 = workbook.createCellStyle();
        font.setBold(true);
        cellStyle11.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
        cellStyle11.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
        cellStyle11.setFont(font);
        cell4.setCellStyle(cellStyle11);

        //</editor-fold>
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 3, 4));
        sheet.addMergedRegion(new CellRangeAddress(keySet.size(), keySet.size(), 1, 3));
        sheet.addMergedRegion(new CellRangeAddress(keySet.size() + 1, keySet.size() + 1, 1, 3));
        sheet.addMergedRegion(new CellRangeAddress(keySet.size() + 2, keySet.size() + 2, 1, 3));

        sheet.setColumnWidth(0, (longestCustomer + 1) * 240);
        sheet.setColumnWidth(1, 8 * 240);
        sheet.setColumnWidth(2, 10 * 240);
        sheet.setColumnWidth(3, 4 * 240);

        int usedSize = 0;
        for (int i = 0; i <= 3; i++) {
            usedSize += sheet.getColumnWidth(i);
        }
        sheet.setColumnWidth(4, (totalSize - usedSize) / 2);
        sheet.setColumnWidth(5, (totalSize - usedSize) / 2);

        Row rowDate = sheet.createRow(keySet.size() + 4);
        Cell cell = rowDate.createCell(0);
        SimpleDateFormat sf = new SimpleDateFormat("EEE MMM yyyy HH:mm:ss");

        cell.setCellValue(sf.format(Calendar.getInstance().getTime()));
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_RIGHT);
        cell.setCellStyle(cellStyle);
        sheet.addMergedRegion(new CellRangeAddress(keySet.size() + 4, keySet.size() + 4, 0, 5));

    }

    try {
        workbook.write(excelOut);
        excelOut.close();
        System.out.println("Done - Packer");
        if (DSC_Main.generateAllReports) {
            DSC_Main.reportsDone++;
            if (DSC_Main.reportsDone == DSC_Main.TOTAL_REPORTS) {
                DSC_Main.reportsDone();
            }
        } else {
            packerLoadingObj.setVisible(false);
            packerLoadingObj.dispose();
            JOptionPane.showMessageDialog(null, "PackerReport Succesfully Generated", "Success",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    } catch (IOException io) {
        packerLoadingObj.setVisible(false);
        packerLoadingObj.dispose();
        JOptionPane.showMessageDialog(null, "An error occured\nCould not create PackerReport", "Error",
                JOptionPane.ERROR_MESSAGE);
        System.err.println("Error - Could not create new PackerReport: ");
        io.printStackTrace();
    }

}

From source file:egovframework.rte.fdl.excel.EgovExcelXSSFServiceTest.java

License:Apache License

/**
 * [Flow #-3]  ? ?  :  ?? ?(? ?, Border? ?, ? ?,  )? 
 *//*from w  w  w  .  ja v  a2  s .  co  m*/
@Test
public void testWriteExcelFileAttribute() throws Exception {

    try {
        LOGGER.debug("testWriteExcelFileAttribute start....");

        short rowheight = 40 * 10;
        int columnwidth = 30;

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testWriteExcelFileAttribute.xlsx");

        // delete file
        if (EgovFileUtil.isExistsFile(sb.toString())) {
            EgovFileUtil.delete(new File(sb.toString()));

            LOGGER.debug("Delete file....{}", sb.toString());
        }

        XSSFWorkbook wb = new XSSFWorkbook();

        XSSFSheet sheet1 = wb.createSheet("new sheet");
        wb.createSheet("second sheet");

        // ? ?
        sheet1.setDefaultRowHeight(rowheight);
        sheet1.setDefaultColumnWidth(columnwidth);

        Font f2 = wb.createFont();
        XSSFCellStyle cs = wb.createCellStyle();

        cs.setFont(f2);
        cs.setWrapText(true);

        // 
        cs.setAlignment(CellStyle.ALIGN_RIGHT);
        cs.setFillPattern(CellStyle.DIAMONDS); //  ?

        XSSFRow r1 = sheet1.createRow(0);
        r1.createCell(0);

        // ? ?
        cs.setFillForegroundColor(IndexedColors.BLUE.getIndex()); //  
        cs.setFillBackgroundColor(IndexedColors.RED.getIndex()); // 

        sheet1.setDefaultColumnStyle((short) 0, cs);

        Workbook tmp = excelService.createWorkbook(wb, sb.toString());

        Sheet sheetTmp1 = tmp.getSheetAt(0);

        assertEquals(rowheight, sheetTmp1.getDefaultRowHeight());
        assertEquals(columnwidth, sheetTmp1.getDefaultColumnWidth());

        CellStyle cs1 = tmp.getCellStyleAt((short) (tmp.getNumCellStyles() - 1));

        LOGGER.debug("getAlignment : {}", cs1.getAlignment());
        assertEquals(XSSFCellStyle.ALIGN_RIGHT, cs1.getAlignment());

        LOGGER.debug("getFillPattern : {}", cs1.getFillPattern());
        assertEquals(XSSFCellStyle.DIAMONDS, cs1.getFillPattern());

        LOGGER.debug("getFillForegroundColor : {}", cs1.getFillForegroundColor());
        LOGGER.debug("getFillBackgroundColor : {}", cs1.getFillBackgroundColor());

        LOGGER.debug(
                "XSSFWorkbook.getFillBackgroundColor(), XSSFColor().getIndexed() ? ? 0 ? ?");

        assertEquals(IndexedColors.BLUE.getIndex(), cs1.getFillForegroundColor());
        assertEquals(IndexedColors.RED.getIndex(), cs1.getFillBackgroundColor());

    } catch (Exception e) {
        LOGGER.error(e.toString());
        throw new Exception(e);
    } finally {
        LOGGER.debug("testWriteExcelFileAttribute end....");
    }
}

From source file:egovframework.rte.fdl.excel.EgovExcelXSSFServiceTest.java

License:Apache License

/**
 * [Flow #-6]  ?  :  ? ?(?, ? )? //from   w w w.  j  av  a  2 s.c  om
 */
@Test
public void testModifyCellAttribute() throws Exception {

    try {
        LOGGER.debug("testModifyCellAttribute start....");

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testModifyCellAttribute.xlsx");

        if (EgovFileUtil.isExistsFile(sb.toString())) {
            EgovFileUtil.delete(new File(sb.toString()));

            LOGGER.debug("Delete file....{}", sb.toString());
        }

        Workbook wbTmp = new XSSFWorkbook();
        wbTmp.createSheet();

        //  ? ?
        excelService.createWorkbook(wbTmp, sb.toString());

        //  ? 
        XSSFWorkbook wb = excelService.loadWorkbook(sb.toString(), new XSSFWorkbook());
        LOGGER.debug("testModifyCellAttribute after loadWorkbook....");

        Sheet sheet = wb.createSheet("cell test sheet2");
        sheet.setColumnWidth((short) 3, (short) 200); // column Width

        CellStyle cs = wb.createCellStyle();
        XSSFFont font = wb.createFont();
        font.setFontHeight(16);
        font.setBoldweight((short) 3);
        font.setFontName("fixedsys");

        cs.setFont(font);
        cs.setAlignment(XSSFCellStyle.ALIGN_RIGHT); // cell 
        cs.setWrapText(true);

        for (int i = 0; i < 100; i++) {
            Row row = sheet.createRow(i);
            row.setHeight((short) 300); // row? height 

            for (int j = 0; j < 5; j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(new XSSFRichTextString("row " + i + ", cell " + j));
                cell.setCellStyle(cs);
            }
        }

        //  ? 
        FileOutputStream out = new FileOutputStream(sb.toString());
        wb.write(out);
        out.close();

        //////////////////////////////////////////////////////////////////////////
        // ?
        XSSFWorkbook wbT = excelService.loadWorkbook(sb.toString(), new XSSFWorkbook());
        Sheet sheetT = wbT.getSheet("cell test sheet2");
        LOGGER.debug("getNumCellStyles : {}", wbT.getNumCellStyles());

        XSSFCellStyle cs1 = (XSSFCellStyle) wbT.getCellStyleAt((short) (wbT.getNumCellStyles() - 1));

        XSSFFont fontT = cs1.getFont();
        LOGGER.debug("font getFontHeight : {}", fontT.getFontHeight());
        LOGGER.debug("font getBoldweight : {}", fontT.getBoldweight());
        LOGGER.debug("font getFontName : {}", fontT.getFontName());
        LOGGER.debug("getAlignment : {}", cs1.getAlignment());
        LOGGER.debug("getWrapText : {}", cs1.getWrapText());

        for (int i = 0; i < 100; i++) {
            Row row1 = sheetT.getRow(i);
            for (int j = 0; j < 5; j++) {
                Cell cell1 = row1.getCell(j);
                LOGGER.debug("row {}, cell {} : {}", i, j, cell1.getRichStringCellValue());
                assertEquals(320, fontT.getFontHeight());
                assertEquals(400, fontT.getBoldweight());
                LOGGER.debug("fontT.getBoldweight()? ? 400? ?");

                assertEquals(XSSFCellStyle.ALIGN_RIGHT, cs1.getAlignment());
                assertTrue(cs1.getWrapText());
            }
        }

    } catch (Exception e) {
        LOGGER.error(e.toString());
        throw new Exception(e);
    } finally {
        LOGGER.debug("testModifyCellAttribute end....");
    }
}

From source file:Ekon.PanelVypisFirem.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    XSSFWorkbook workbook = new XSSFWorkbook();

    XSSFSheet sheet = workbook.createSheet("Zamestnanci");
    Map<String, Object[]> data = new TreeMap<>();
    data.put("1",
            new Object[] { "Nazev Firmy", "Mesto", "Ulice", "Kontakt", "Email", "ICO", "DICO", "Kraj", "PSC" });
    int i = 2;//from www  .ja v a2s . c om

    try {
        for (Iterator it = vytvorFirmy.dejIterator(); it.hasNext();) {
            Firma f = (Firma) it.next();
            data.put(String.valueOf(i++), new Object[] { f.getNazevFirmy(), f.getMesto(), f.getUlice(),
                    f.getKontakt(), f.getEmail(), f.getIco(), f.getDico(), f.getKraj(), f.getPsc() });
        }

        Set<String> keySet = data.keySet();
        int rowNum = 0;
        for (String key : keySet) {
            Row row = sheet.createRow(rowNum++);
            Object[] objArr = data.get(key);
            int cellNum = 0;
            for (Object obj : objArr) {
                Cell cell = row.createCell(cellNum++);
                if (obj instanceof String) {
                    cell.setCellValue((String) obj);
                } else if (obj instanceof Integer) {
                    cell.setCellValue((Integer) obj);
                }
            }

        }

        JFileChooser fch = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("objects xls xlsx", "xls", "xlsx");
        fch.setFileFilter(filter);
        int returnVal = fch.showSaveDialog(this);

        File nazevSouboru = fch.getSelectedFile();
        FileOutputStream out = new FileOutputStream(nazevSouboru.getAbsolutePath());
        workbook.write(out);
        out.close();
        JOptionPane.showMessageDialog(this, "Sobour XLS/XLSX vytvoren", "Informace", 1);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Chyba !", "Error", 1);
    }

}

From source file:Ekon.PanelVypisZamestnancu.java

private void btnUlozXLSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUlozXLSActionPerformed
    XSSFWorkbook workbook = new XSSFWorkbook();

    XSSFSheet sheet = workbook.createSheet("Zamestnanci");
    Map<String, Object[]> data = new TreeMap<>();
    data.put("1", new Object[] { "Jmeno", "Prijmeni", "Mesto", "Ulice", "PSC", "Kraj", "Titul",
            "Datum narozeni", "Email", "Telefonni cislo", "Rodne cislo", "Narodnost", "Pozice" });
    int i = 2;/*from   ww  w.j  a  v a 2 s .  com*/
    for (Iterator it = aktualniFirma.dejIteratorZamestnancu(); it.hasNext();) {
        Zamestnanec z = (Zamestnanec) it.next();
        data.put(String.valueOf(i++),
                new Object[] { z.getJmeno(), z.getPrijmeni(), z.getMesto(), z.getUlice(), z.getPsc(),
                        z.getKraj(), z.getTitul(), z.getDatumNarozeni(), z.getEmail(), z.getTelefoniCislo(),
                        z.getRodneCislo(), z.getNarodnost(), z.getPozice() });
    }

    Set<String> keySet = data.keySet();
    int rowNum = 0;
    for (String key : keySet) {
        Row row = sheet.createRow(rowNum++);
        Object[] objArr = data.get(key);
        int cellNum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellNum++);
            if (obj instanceof String) {
                cell.setCellValue((String) obj);
            } else if (obj instanceof Integer) {
                cell.setCellValue((Integer) obj);
            }
        }

    }

    JFileChooser fch = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("objects xls xlsx", "xls", "xlsx");
    fch.setFileFilter(filter);
    int returnVal = fch.showSaveDialog(this);

    try {
        File nazevSouboru = fch.getSelectedFile();
        FileOutputStream out = new FileOutputStream(nazevSouboru.getAbsolutePath());
        workbook.write(out);
        out.close();
        JOptionPane.showMessageDialog(this, "Sobour XLS/XLSX vytvoren", "Informace", 1);
    } catch (Exception e) {
    }

}

From source file:es.tena.foundation.util.POIUtil.java

public static void generateXLS(String tabla, String filename, Connection conn, String encoding)
        throws SQLException {
    String query = "";
    try {//from   w  ww.  ja  v  a  2 s .c  o  m
        query = "SELECT * FROM (" + tabla + ")";
        PreparedStatement stmt = conn.prepareStatement(query);
        ResultSet rset = stmt.executeQuery();

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet(filename);
        String sheetRef = sheet.getPackagePart().getPartName().getName();
        String template = "c:\\temp\\template_" + filename + ".xlsx";
        FileOutputStream os = new FileOutputStream(template);
        wb.write(os);
        os.close();

        File tmp = File.createTempFile("sheet", ".xml");
        Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), encoding);
        generate(fw, rset, encoding);
        rset.close();
        stmt.close();
        fw.close();

        FileOutputStream out = new FileOutputStream(
                "c:\\temp\\" + filename + sdf.format(calendario.getTime()) + ".xlsx");
        FileUtil.substitute(new File(template), tmp, sheetRef.substring(1), out);
        out.close();
        Logger.getLogger(POIUtil.class.getName()).log(Level.INFO, "Creado con exito {0}", filename);
    } catch (Exception ex) {
        ex.printStackTrace();
        Logger.getLogger(POIUtil.class.getName()).log(Level.SEVERE, null, query + "\n" + ex);
        System.out.println(query);
    } finally {
        conn.close();
    }
}

From source file:es.upm.oeg.tools.rdfshapes.libdemo.ApachePoiDemo.java

License:Apache License

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

    String filename = "test.xls";

    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet("Cardinality");

    //iterating r number of rows
    for (int r = 0; r < 5; r++) {
        XSSFRow row = sheet.createRow(r);

        //iterating c number of columns
        for (int c = 0; c < 5; c++) {
            XSSFCell cell = row.createCell(c);

            cell.setCellValue("Cell " + r + " " + c);
        }/*w  w  w. j ava2  s.co  m*/
    }

    FileOutputStream fileOut = new FileOutputStream(filename);
    wb.write(fileOut);
    fileOut.close();

}

From source file:es.upm.oeg.tools.rdfshapes.patterns.DatatypeObjectPropertyPatterns.java

License:Apache License

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

    String endpoint = "http://3cixty.eurecom.fr/sparql";

    List<String> classList = Files.readAllLines(Paths.get(classListPath), Charset.defaultCharset());

    String classPropertyQueryString = readFile(classPropertyQueryPath, Charset.defaultCharset());
    String propertyCardinalityQueryString = readFile(propertyCardinalityQueryPath, Charset.defaultCharset());
    String individualCountQueryString = readFile(individualCountQueryPath, Charset.defaultCharset());
    String objectCountQueryString = readFile(objectCountQueryPath, Charset.defaultCharset());
    String tripleCountQueryString = readFile(tripleCountQueryPath, Charset.defaultCharset());
    String literalCountQueryString = readFile(literalCountQueryPath, Charset.defaultCharset());
    String blankCountQueryString = readFile(blankCountQueryPath, Charset.defaultCharset());
    String iriCountQueryString = readFile(iriCountQueryPath, Charset.defaultCharset());
    String datatypeCountQueryString = readFile(datatypeCountsPath, Charset.defaultCharset());

    DecimalFormat df = new DecimalFormat("0.0000");

    //Create the Excel workbook and sheet
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet("Cardinality");

    int currentExcelRow = 0;
    int classStartRow = 0;

    for (String clazz : classList) {

        System.out.println("Class: " + clazz);

        Map<String, String> litMap = new HashMap<>();
        Map<String, String> iriMap = ImmutableMap.of("class", clazz);

        String queryString = bindQueryString(individualCountQueryString,
                ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));

        int individualCount;
        List<RDFNode> c = executeQueryForList(queryString, endpoint, "c");
        if (c.size() == 1) {
            individualCount = c.get(0).asLiteral().getInt();
        } else {//w  w  w  . j  ava  2  s .co m
            continue;
        }

        // If there are zero individuals, continue
        if (individualCount == 0) {
            throw new IllegalStateException("Check whether " + classListPath + " and " + endpoint + " match.");
        }

        classStartRow = currentExcelRow;
        XSSFRow row = sheet.createRow(currentExcelRow);
        XSSFCell cell = row.createCell(0);
        cell.setCellValue(clazz);

        litMap = new HashMap<>();
        iriMap = ImmutableMap.of("class", clazz);
        queryString = bindQueryString(classPropertyQueryString,
                ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));
        List<RDFNode> nodeList = executeQueryForList(queryString, endpoint, "p");

        //            System.out.println("***");
        //            System.out.println("### **" + clazz + "**");
        //            System.out.println("***");
        //            System.out.println();

        cell.getCellStyle().setAlignment(CellStyle.ALIGN_CENTER);

        for (RDFNode property : nodeList) {
            if (property.isURIResource()) {

                System.out.println("          " + property);

                int tripleCount;
                int objectCount;
                int literalCount;
                int blankCount;
                int iriCount;

                String propertyURI = property.asResource().getURI();

                XSSFRow propertyRow = sheet.getRow(currentExcelRow);
                if (propertyRow == null) {
                    propertyRow = sheet.createRow(currentExcelRow);
                }
                currentExcelRow++;
                XSSFCell propertyCell = propertyRow.createCell(1);
                propertyCell.setCellValue(propertyURI);

                litMap = new HashMap<>();
                iriMap = ImmutableMap.of("class", clazz, "p", propertyURI);

                queryString = bindQueryString(tripleCountQueryString,
                        ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));

                c = executeQueryForList(queryString, endpoint, "c");
                if (c.size() > 0) {
                    tripleCount = c.get(0).asLiteral().getInt();
                } else {
                    tripleCount = 0;
                }

                queryString = bindQueryString(objectCountQueryString,
                        ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));

                c = executeQueryForList(queryString, endpoint, "c");
                if (c.size() > 0) {
                    objectCount = c.get(0).asLiteral().getInt();
                } else {
                    objectCount = 0;
                }

                queryString = bindQueryString(literalCountQueryString,
                        ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));
                c = executeQueryForList(queryString, endpoint, "c");
                if (c.size() > 0) {
                    literalCount = c.get(0).asLiteral().getInt();
                } else {
                    literalCount = 0;
                }

                queryString = bindQueryString(blankCountQueryString,
                        ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));
                c = executeQueryForList(queryString, endpoint, "c");
                if (c.size() > 0) {
                    blankCount = c.get(0).asLiteral().getInt();
                } else {
                    blankCount = 0;
                }

                queryString = bindQueryString(iriCountQueryString,
                        ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));
                c = executeQueryForList(queryString, endpoint, "c");
                if (c.size() > 0) {
                    iriCount = c.get(0).asLiteral().getInt();
                } else {
                    iriCount = 0;
                }

                XSSFCell objectCountCell = propertyRow.createCell(2);
                objectCountCell.setCellValue(objectCount);

                XSSFCell uniqueObjectsCell = propertyRow.createCell(3);
                uniqueObjectsCell.setCellValue(df.format(((double) objectCount) / tripleCount));

                XSSFCell literalCell = propertyRow.createCell(4);
                literalCell.setCellValue(df.format((((double) literalCount) / objectCount)));

                XSSFCell iriCell = propertyRow.createCell(5);
                iriCell.setCellValue(df.format((((double) iriCount) / objectCount)));

                XSSFCell blankCell = propertyRow.createCell(6);
                blankCell.setCellValue(df.format((((double) blankCount) / objectCount)));

                if (literalCount > 0) {

                    litMap = new HashMap<>();
                    iriMap = ImmutableMap.of("class", clazz, "p", propertyURI);

                    queryString = bindQueryString(datatypeCountQueryString,
                            ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));
                    List<Map<String, RDFNode>> solnMaps = executeQueryForList(queryString, endpoint,
                            ImmutableSet.of("datatype", "c"));

                    int i = 1;
                    for (Map<String, RDFNode> soln : solnMaps) {
                        String datatype = soln.get("datatype").asResource().getURI();
                        int count = soln.get("c").asLiteral().getInt();

                        XSSFCell dataCell = propertyRow.createCell(6 + i++);
                        dataCell.setCellValue(datatype);

                        dataCell = propertyRow.createCell(6 + i++);
                        dataCell.setCellValue(df.format((((double) count) / objectCount)));

                    }

                }

                //                    System.out.println("* " + propertyURI);
                //                    System.out.println();
                //
                //                    System.out.println("| Object Count | Unique Objects | Literals | IRIs | Blank Nodes | ");
                //                    System.out.println("|---|---|---|---|---|");
                //                    System.out.println(String.format("|%d|%d (%.2f%%) |%d (%.2f%%)|%d (%.2f%%)|%d (%.2f%%)|",
                //                            tripleCount,
                //                            objectCount, ((((double) objectCount)/tripleCount)*100),
                //                            literalCount, ((((double) literalCount)/objectCount)*100),
                //                            iriCount, ((((double) iriCount)/objectCount)*100),
                //                            blankCount, ((((double) blankCount)/objectCount)*100)));
                //                    System.out.println();
            }
        }
    }

    String filename = "literals.xls";
    FileOutputStream fileOut = new FileOutputStream(filename);
    wb.write(fileOut);
    fileOut.close();

}

From source file:es.upm.oeg.tools.rdfshapes.utils.CadinalityResultGenerator.java

License:Apache License

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

    String endpoint = "http://3cixty.eurecom.fr/sparql";

    List<String> classList = Files.readAllLines(Paths.get(classListPath), Charset.defaultCharset());

    String classPropertyQueryString = readFile(classPropertyQueryPath, Charset.defaultCharset());
    String propertyCardinalityQueryString = readFile(propertyCardinalityQueryPath, Charset.defaultCharset());
    String individualCountQueryString = readFile(individualCountQueryPath, Charset.defaultCharset());

    DecimalFormat df = new DecimalFormat("0.0000");

    //Create the Excel workbook and sheet
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet("Cardinality");

    int currentExcelRow = 0;
    int classStartRow = 0;

    for (String clazz : classList) {

        Map<String, String> litMap = new HashMap<>();
        Map<String, String> iriMap = ImmutableMap.of("class", clazz);

        String queryString = bindQueryString(individualCountQueryString,
                ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));

        int individualCount;
        List<RDFNode> c = executeQueryForList(queryString, endpoint, "c");
        if (c.size() == 1) {
            individualCount = c.get(0).asLiteral().getInt();
        } else {/*w  w  w  .j a  v a2 s .  c  o m*/
            continue;
        }

        // If there are zero individuals, continue
        if (individualCount == 0) {
            throw new IllegalStateException("Check whether " + classListPath + " and " + endpoint + " match.");
        }

        //            System.out.println("***");
        //            System.out.println("### **" + clazz + "** (" + individualCount + ")");
        //            System.out.println("***");
        //            System.out.println();

        classStartRow = currentExcelRow;
        XSSFRow row = sheet.createRow(currentExcelRow);
        XSSFCell cell = row.createCell(0);
        cell.setCellValue(clazz);
        cell.getCellStyle().setAlignment(CellStyle.ALIGN_CENTER);

        queryString = bindQueryString(classPropertyQueryString,
                ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap));

        List<RDFNode> nodeList = executeQueryForList(queryString, endpoint, "p");

        for (RDFNode property : nodeList) {
            if (property.isURIResource()) {

                DescriptiveStatistics stats = new DescriptiveStatistics();

                String propertyURI = property.asResource().getURI();
                //                    System.out.println("* " + propertyURI);
                //                    System.out.println();

                XSSFRow propertyRow = sheet.getRow(currentExcelRow);
                if (propertyRow == null) {
                    propertyRow = sheet.createRow(currentExcelRow);
                }
                currentExcelRow++;

                XSSFCell propertyCell = propertyRow.createCell(1);
                propertyCell.setCellValue(propertyURI);

                Map<String, String> litMap2 = new HashMap<>();
                Map<String, String> iriMap2 = ImmutableMap.of("class", clazz, "p", propertyURI);

                queryString = bindQueryString(propertyCardinalityQueryString,
                        ImmutableMap.of(IRI_BINDINGS, iriMap2, LITERAL_BINDINGS, litMap2));

                List<Map<String, RDFNode>> solnMaps = executeQueryForList(queryString, endpoint,
                        ImmutableSet.of("card", "count"));

                int sum = 0;
                List<CardinalityCount> cardinalityList = new ArrayList<>();
                if (solnMaps.size() > 0) {

                    for (Map<String, RDFNode> soln : solnMaps) {
                        int count = soln.get("count").asLiteral().getInt();
                        int card = soln.get("card").asLiteral().getInt();

                        for (int i = 0; i < count; i++) {
                            stats.addValue(card);
                        }

                        CardinalityCount cardinalityCount = new CardinalityCount(card, count,
                                (((double) count) / individualCount) * 100);
                        cardinalityList.add(cardinalityCount);
                        sum += count;
                    }

                    // Check for zero cardinality instances
                    int count = individualCount - sum;
                    if (count > 0) {
                        for (int i = 0; i < count; i++) {
                            stats.addValue(0);
                        }
                        CardinalityCount cardinalityCount = new CardinalityCount(0, count,
                                (((double) count) / individualCount) * 100);
                        cardinalityList.add(cardinalityCount);
                    }
                }

                Map<Integer, Double> cardMap = new HashMap<>();
                for (CardinalityCount count : cardinalityList) {
                    cardMap.put(count.getCardinality(), count.getPrecentage());
                }

                XSSFCell instanceCountCell = propertyRow.createCell(2);
                instanceCountCell.setCellValue(individualCount);

                XSSFCell minCell = propertyRow.createCell(3);
                minCell.setCellValue(stats.getMin());

                XSSFCell maxCell = propertyRow.createCell(4);
                maxCell.setCellValue(stats.getMax());

                XSSFCell p1 = propertyRow.createCell(5);
                p1.setCellValue(stats.getPercentile(1));

                XSSFCell p99 = propertyRow.createCell(6);
                p99.setCellValue(stats.getPercentile(99));

                XSSFCell mean = propertyRow.createCell(7);
                mean.setCellValue(df.format(stats.getMean()));

                for (int i = 0; i < 21; i++) {
                    XSSFCell dataCell = propertyRow.createCell(8 + i);
                    Double percentage = cardMap.get(i);
                    if (percentage != null) {
                        dataCell.setCellValue(df.format(percentage));
                    } else {
                        dataCell.setCellValue(0);
                    }
                }

                //                    System.out.println("| Min Card. |Max Card. |");
                //                    System.out.println("|---|---|");
                //                    System.out.println("| ? | ? |");
                //                    System.out.println();

            }
        }

        //System.out.println("class start: " + classStartRow + ", class end: " + (currentExcelRow -1));
        //We have finished writting properties of one class, now it's time to merge the cells
        int classEndRow = currentExcelRow - 1;
        if (classStartRow < classEndRow) {
            sheet.addMergedRegion(new CellRangeAddress(classStartRow, classEndRow, 0, 0));
        }

    }

    String filename = "3cixty.xls";
    FileOutputStream fileOut = new FileOutputStream(filename);
    wb.write(fileOut);
    fileOut.close();
}