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

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

Introduction

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

Prototype

public XSSFWorkbook() 

Source Link

Document

Create a new SpreadsheetML workbook.

Usage

From source file:com.crm.webapp.util.ExcelCustomExporter.java

License:Apache License

@Override
public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle,
        boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, boolean subTable) throws IOException {

    wb = new XSSFWorkbook();
    String safeName = WorkbookUtil.createSafeSheetName(filename);
    Sheet sheet = wb.createSheet(safeName);

    cellStyle = wb.createCellStyle();//from  www.  ja v  a  2  s.  c  o m
    facetStyle = wb.createCellStyle();
    titleStyle = wb.createCellStyle();
    createCustomFonts();

    int maxColumns = 0;
    StringTokenizer st = new StringTokenizer(tableId, ",");
    while (st.hasMoreElements()) {
        String tableName = (String) st.nextElement();
        UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(),
                tableName);
        if (component == null) {
            throw new FacesException("Cannot find component \"" + tableName + "\" in view.");
        }
        if (!(component instanceof DataTable || component instanceof DataList)) {
            throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName()
                    + "\", exporter must target a PrimeFaces DataTable/DataList.");
        }

        DataList list = null;
        DataTable table = null;
        int cols = 0;
        if (preProcessor != null) {
            preProcessor.invoke(context.getELContext(), new Object[] { wb });
        }
        if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) {
            Row titleRow = sheet.createRow(sheet.getLastRowNum());
            int cellIndex = titleRow.getLastCellNum() == -1 ? 0 : titleRow.getLastCellNum();
            Cell cell = titleRow.createCell(cellIndex);
            cell.setCellValue(new XSSFRichTextString(tableTitle));
            Font titleFont = wb.createFont();
            titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
            titleStyle.setFont(titleFont);
            cell.setCellStyle(titleStyle);
            sheet.createRow(sheet.getLastRowNum() + 3);

        }
        if (component instanceof DataList) {
            list = (DataList) component;

            if (list.getHeader() != null) {
                tableFacet(context, sheet, list, "header");
            }
            if (pageOnly) {
                exportPageOnly(context, list, sheet);
            } else {
                exportAll(context, list, sheet);
            }
            cols = list.getRowCount();
        } else {

            table = (DataTable) component;
            int columnsCount = getColumnsCount(table);

            if (table.getHeader() != null && !subTable) {
                tableFacet(context, sheet, table, columnsCount, "header");

            }
            if (!subTable) {
                tableColumnGroup(sheet, table, "header");
            }

            addColumnFacets(table, sheet, ColumnType.HEADER);

            if (pageOnly) {
                exportPageOnly(context, table, sheet);
            } else if (selectionOnly) {
                exportSelectionOnly(context, table, sheet);
            } else {
                exportAll(context, table, sheet, subTable);
            }

            if (table.hasFooterColumn() && !subTable) {
                addColumnFacets(table, sheet, ColumnType.FOOTER);
            }
            if (!subTable) {
                tableColumnGroup(sheet, table, "footer");
            }
            table.setRowIndex(-1);
            if (postProcessor != null) {
                postProcessor.invoke(context.getELContext(), new Object[] { wb });
            }
            cols = table.getColumnsCount();

            if (maxColumns < cols) {
                maxColumns = cols;
            }
        }
        sheet.createRow(sheet.getLastRowNum() + Integer.parseInt(datasetPadding));
    }

    if (!subTable)
        for (int i = 0; i < maxColumns; i++) {
            sheet.autoSizeColumn((short) i);
        }

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    printSetup.setPaperSize(PrintSetup.A4_PAPERSIZE);
    sheet.setPrintGridlines(true);

    writeExcelToResponse(context.getExternalContext(), wb, filename);

}

From source file:com.dao.DatabaseDao.java

public static void exportDB(String destpath) {
    try {/*from w w  w. j a  v  a2 s.c om*/

        DB db = new DB();
        Connection c = db.getConnection();

        Statement st = c.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM EMPLOYEE_INFO");

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("EmployeeInfo");
        XSSFRow row = sheet.createRow(0);

        row.createCell(0, CellType.STRING).setCellValue("ID");
        row.createCell(1, CellType.STRING).setCellValue("NAME");
        row.createCell(2, CellType.STRING).setCellValue("RECEIPT_NO");
        row.createCell(3, CellType.STRING).setCellValue("ENTRY_DATE");
        row.createCell(4, CellType.STRING).setCellValue("SUB_RATE");
        row.createCell(5, CellType.STRING).setCellValue("JAN");
        row.createCell(6, CellType.STRING).setCellValue("FEB");
        row.createCell(7, CellType.STRING).setCellValue("MAR");
        row.createCell(8, CellType.STRING).setCellValue("APR");
        row.createCell(9, CellType.STRING).setCellValue("MAY");
        row.createCell(10, CellType.STRING).setCellValue("JUN");
        row.createCell(11, CellType.STRING).setCellValue("JUL");
        row.createCell(12, CellType.STRING).setCellValue("AUG");
        row.createCell(13, CellType.STRING).setCellValue("SEP");
        row.createCell(14, CellType.STRING).setCellValue("OCT");
        row.createCell(15, CellType.STRING).setCellValue("NOV");
        row.createCell(16, CellType.STRING).setCellValue("DECB");
        row.createCell(17, CellType.STRING).setCellValue("TOTAL");
        row.createCell(18, CellType.STRING).setCellValue("REMARK");
        row.createCell(19, CellType.STRING).setCellValue("SECTOR");
        row.createCell(20, CellType.STRING).setCellValue("SUB_FROM");
        row.createCell(21, CellType.STRING).setCellValue("SUB_TO");
        row.createCell(22, CellType.STRING).setCellValue("PLACE");

        int i = 1;
        while (rs.next()) {
            row = sheet.createRow(i);

            row.createCell(0, CellType.STRING).setCellValue(rs.getLong("ID"));
            row.createCell(1, CellType.STRING).setCellValue(rs.getString("NAME"));
            row.createCell(2, CellType.STRING).setCellValue(rs.getLong("RECEIPT_NO"));
            row.createCell(3, CellType.STRING).setCellValue(rs.getDate("ENTRY_DATE"));
            row.createCell(4, CellType.STRING).setCellValue(rs.getInt("SUB_RATE"));
            row.createCell(5, CellType.STRING).setCellValue(rs.getInt("JAN"));
            row.createCell(6, CellType.STRING).setCellValue(rs.getInt("FEB"));
            row.createCell(7, CellType.STRING).setCellValue(rs.getInt("MAR"));
            row.createCell(8, CellType.STRING).setCellValue(rs.getInt("APR"));
            row.createCell(9, CellType.STRING).setCellValue(rs.getInt("MAY"));
            row.createCell(10, CellType.STRING).setCellValue(rs.getInt("JUN"));
            row.createCell(11, CellType.STRING).setCellValue(rs.getInt("JUL"));
            row.createCell(12, CellType.STRING).setCellValue(rs.getInt("AUG"));
            row.createCell(13, CellType.STRING).setCellValue(rs.getInt("SEP"));
            row.createCell(14, CellType.STRING).setCellValue(rs.getInt("OCT"));
            row.createCell(15, CellType.STRING).setCellValue(rs.getInt("NOV"));
            row.createCell(16, CellType.STRING).setCellValue(rs.getInt("DECB"));
            row.createCell(17, CellType.STRING).setCellValue(rs.getLong("TOTAL"));
            row.createCell(18, CellType.STRING).setCellValue(rs.getString("REMARK"));
            row.createCell(19, CellType.STRING).setCellValue(rs.getString("SECTOR"));
            row.createCell(20, CellType.STRING).setCellValue(rs.getString("SUB_FROM"));
            row.createCell(21, CellType.STRING).setCellValue(rs.getString("SUB_TO"));
            row.createCell(22, CellType.STRING).setCellValue(rs.getString("PLACE"));

            i++;
        }

        Calendar cal = Calendar.getInstance();
        String filename = "BMSBackup_" + cal.get(Calendar.DAY_OF_MONTH) + "_" + (cal.get(Calendar.MONTH) + 1)
                + "_" + cal.get(Calendar.YEAR) + ".xlsx";
        FileOutputStream fout = new FileOutputStream(destpath + "\\" + filename);
        wb.write(fout);
        fout.flush();
        fout.close();

    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "Database Exporting Error..." + e.getMessage(), "Error Message",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.dataart.spreadsheetanalytics.engine.ConverterUtils.java

License:Apache License

/** Creates an instance of new {@link XSSFWorkbook}. */
public static Workbook newWorkbook() {
    Workbook book = new XSSFWorkbook();
    book.addToolPack(Functions.getUdfFinder());
    return book;//from w  w w.j  a  v  a  2s. c  o  m
}

From source file:com.dbumama.market.web.core.render.excel.PoiExporter.java

License:Apache License

public Workbook export() {
    Preconditions.checkNotNull(data, "data can not be null");
    Preconditions.checkNotNull(headers, "headers can not be null");
    Preconditions.checkNotNull(columns, "columns can not be null");
    Preconditions.checkArgument(//from  w  w  w .  j  a  va  2  s .c o  m
            data.length == sheetNames.length && sheetNames.length == headers.length
                    && headers.length == columns.length,
            "data,sheetNames,headers and columns'length should be the same." + "(data:" + data.length
                    + ",sheetNames:" + sheetNames.length + ",headers:" + headers.length + ",columns:"
                    + columns.length + ")");
    Preconditions.checkArgument(cellWidth >= 0, "cellWidth can not be less than 0");
    Workbook wb;
    if (VERSION_2003.equals(version)) {
        wb = new HSSFWorkbook();
        if (data.length > 1) {
            for (int i = 0; i < data.length; i++) {
                List<?> item = data[i];
                Preconditions.checkArgument(item.size() < MAX_ROWS,
                        "Data [" + i + "] is invalid:invalid data size (" + item.size()
                                + ") outside allowable range (0..65535)");
            }
        } else if (data.length == 1 && data[0].size() > MAX_ROWS) {
            data = dice(data[0], MAX_ROWS).toArray(new List<?>[] {});
            String sheetName = sheetNames[0];
            sheetNames = new String[data.length];
            for (int i = 0; i < data.length; i++) {
                sheetNames[i] = sheetName + (i == 0 ? "" : (i + 1));
            }
            String[] header = headers[0];
            headers = new String[data.length][];
            for (int i = 0; i < data.length; i++) {
                headers[i] = header;
            }
            String[] column = columns[0];
            columns = new String[data.length][];
            for (int i = 0; i < data.length; i++) {
                columns[i] = column;
            }
        }
    } else {
        wb = new XSSFWorkbook();
    }
    if (data.length == 0) {
        return wb;
    }
    for (int i = 0; i < data.length; i++) {
        Sheet sheet = wb.createSheet(sheetNames[i]);
        Row row;
        Cell cell;
        if (headers[i].length > 0) {
            row = sheet.createRow(0);
            if (headerRow <= 0) {
                headerRow = HEADER_ROW;
            }
            headerRow = Math.min(headerRow, MAX_ROWS);
            for (int h = 0, lenH = headers[i].length; h < lenH; h++) {
                if (cellWidth > 0) {
                    sheet.setColumnWidth(h, cellWidth);
                }
                cell = row.createCell(h);
                cell.setCellValue(headers[i][h]);
            }
        }

        for (int j = 0, len = data[i].size(); j < len; j++) {
            row = sheet.createRow(j + headerRow);
            Object obj = data[i].get(j);
            if (obj == null) {
                continue;
            }
            if (obj instanceof Map) {
                processAsMap(columns[i], row, obj);
            } else if (obj instanceof Model) {
                processAsModel(columns[i], row, obj);
            } else if (obj instanceof Record) {
                processAsRecord(columns[i], row, obj);
            } else {
                throw new RuntimeException("Not support type[" + obj.getClass() + "]");
            }
        }
    }
    return wb;
}

From source file:com.dfpray.formatter.CardModel.java

/**
 * Exports List of B.C to Excel file, Path should include name and format .xlsx ending
 * @param path//from   www. jav  a2 s  .  c o  m
 * @throws IOException 
 */
public void exportToExcel(String path) throws IOException {
    System.out.println("Called ");

    BusinessCard card;
    Cell cell;
    String[] info;
    Double number;
    String cardInfo;
    Row row;

    //Create Blank workbook/sheet
    @SuppressWarnings("resource")
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Business Data");
    String[] tmpArray = { "CompanyName", "ContactFirstName", "ContactLastName", "Title", "Street Address",
            "Suite/PO Box", "City", "State", "ZipCode", "Country", "PhoneNumber", "Extension", "MobilePhone",
            "FaxNumber", "EmailAddress", "Website", "CsiCodes", "CompanyFunction", "MBEAffiliations", "Labor",
            "ServiceArea", "CompanyNotes", "ContactLists", "CF_Alternate Email", "CF_Do Not Use",
            "CF_Supplier/Manuf", "CF_Trade", "CF_Union Value", "CF_Unlicensed States", "CF_Will Not Bid" };

    Font headerFont = workbook.createFont();
    headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);

    XSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setFont(headerFont);

    XSSFCellStyle cellStyle2 = workbook.createCellStyle();
    cellStyle2.setFont(headerFont);
    cellStyle2.setFillPattern(CellStyle.SOLID_FOREGROUND);
    cellStyle2.setFillForegroundColor(IndexedColors.YELLOW.getIndex());

    //Write Template

    row = sheet.createRow(0);
    for (int k = 0; k < 30; k++) {
        cell = row.createCell(k);
        cell.setCellStyle(cellStyle);

        if (k == 0 || k == 13 || k == 14 || k == 16 || k == 17) {
            cell.setCellStyle(cellStyle2);
        }

        cell.setCellValue(tmpArray[k]);
    }

    //Row = Business
    for (int i = 1; i <= amtCards(); i++) {
        row = sheet.createRow(i);
        card = cards.get(i - 1);
        info = card.infoToArray();

        //Create Column = Data for each Business
        for (int k = 0; k < 30; k++) {
            cardInfo = info[k];
            cell = row.createCell(k);

            if (k == 24)
                continue;

            try {
                number = Double.parseDouble(cardInfo);
                cell.setCellValue(number);
            } catch (NumberFormatException e) {
                cell.setCellValue(cardInfo);
            }

        }
        card.setExported(true);
    }

    //Create file system using specific name
    FileOutputStream out;
    try {
        out = new FileOutputStream(new File(path));
    } catch (FileNotFoundException e) {

        //Reset cards to not exported
        for (BusinessCard cardR : cards) {
            cardR.setExported(false);
        }
        throw new IOException();
    }
    workbook.write(out);
    out.close();

}

From source file:com.docdoku.server.export.ExcelGenerator.java

License:Open Source License

public File generateXLSResponse(QueryResult queryResult, Locale locale, String baseURL) {
    File excelFile = new File("export_parts.xls");
    //Blank workbook
    XSSFWorkbook workbook = new XSSFWorkbook();

    //Create a blank sheet
    XSSFSheet sheet = workbook.createSheet("Parts Data");

    String header = StringUtils.join(queryResult.getQuery().getSelects(), ";");
    String[] columns = header.split(";");

    Map<Integer, String[]> data = new HashMap<>();
    String[] headerFormatted = createXLSHeaderRow(header, columns, locale);
    data.put(1, headerFormatted);//  w  w w.  j  av a 2s . c om

    Map<Integer, String[]> commentsData = new HashMap<>();
    String[] headerComments = createXLSHeaderRowComments(header, columns);
    commentsData.put(1, headerComments);

    List<String> selects = queryResult.getQuery().getSelects();
    int i = 1;
    for (QueryResultRow row : queryResult.getRows()) {
        i++;
        data.put(i, createXLSRow(selects, row, baseURL));
        commentsData.put(i, createXLSRowComments(selects, row));
    }

    //Iterate over data and write to sheet
    Set<Integer> keyset = data.keySet();
    int rownum = 0;

    for (Integer key : keyset) {

        Row row = sheet.createRow(rownum++);
        String[] objArr = data.get(key);
        int cellnum = 0;
        for (String obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            cell.setCellValue(obj);
        }

        CreationHelper factory = workbook.getCreationHelper();
        Drawing drawing = sheet.createDrawingPatriarch();
        String[] commentsObjArr = commentsData.get(key);
        cellnum = 0;
        for (String commentsObj : commentsObjArr) {
            if (commentsObj.length() > 0) {
                Cell cell = row.getCell(cellnum) != null ? row.getCell(cellnum) : row.createCell(cellnum);

                // When the comment box is visible, have it show in a 1x3 space
                ClientAnchor anchor = factory.createClientAnchor();
                anchor.setCol1(cell.getColumnIndex());
                anchor.setCol2(cell.getColumnIndex() + 1);
                anchor.setRow1(row.getRowNum());
                anchor.setRow2(row.getRowNum() + 1);

                Comment comment = drawing.createCellComment(anchor);
                RichTextString str = factory.createRichTextString(commentsObj);
                comment.setString(str);

                // Assign the comment to the cell
                cell.setCellComment(comment);
            }
            cellnum++;
        }
    }

    // Define header style
    Font headerFont = workbook.createFont();
    headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    headerFont.setFontHeightInPoints((short) 10);
    headerFont.setFontName("Courier New");
    headerFont.setItalic(true);
    headerFont.setColor(IndexedColors.WHITE.getIndex());
    CellStyle headerStyle = workbook.createCellStyle();
    headerStyle.setFont(headerFont);
    headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

    // Set header style
    for (int j = 0; j < columns.length; j++) {
        Cell cell = sheet.getRow(0).getCell(j);
        cell.setCellStyle(headerStyle);

        if (cell.getCellComment() != null) {
            String comment = cell.getCellComment().getString().toString();

            if (comment.equals(QueryField.CTX_PRODUCT_ID) || comment.equals(QueryField.CTX_SERIAL_NUMBER)
                    || comment.equals(QueryField.PART_MASTER_NUMBER)) {
                for (int k = 0; k < queryResult.getRows().size(); k++) {
                    Cell grayCell = sheet.getRow(k + 1).getCell(j) != null ? sheet.getRow(k + 1).getCell(j)
                            : sheet.getRow(k + 1).createCell(j);
                    grayCell.setCellStyle(headerStyle);
                }
            }
        }
    }

    try {
        //Write the workbook in file system
        FileOutputStream out = new FileOutputStream(excelFile);
        workbook.write(out);
        out.close();
    } catch (Exception e) {
        LOGGER.log(Level.FINEST, null, e);
    }
    return excelFile;

}

From source file:com.dua3.meja.model.poi.PoiWorkbookFactory.java

License:Apache License

/**
 *
 * @param locale/*from   w ww  .j  av a2s  .  c o m*/
 * @return
 */
public Workbook createXlsx(Locale locale) {
    return new PoiXssfWorkbook(new XSSFWorkbook(), locale, null);
}

From source file:com.dufeng.core.BusinessPlan.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;//from  ww w. j  av  a2s.  c o m

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

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

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

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

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

    //the header row: centered text in 48pt font
    Row headerRow = sheet.createRow(0);
    headerRow.setHeightInPoints(12.75f);
    for (int i = 0; i < titles.length; i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellValue(titles[i]);
        cell.setCellStyle(styles.get("header"));
    }
    //columns for 11 weeks starting from 9-Jul
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);

    //calendar.setTime(fmt.parse("9-Jul"));
    calendar.setTime(new Date());
    calendar.set(Calendar.YEAR, year);
    for (int i = 0; i < 11; i++) {
        Cell cell = headerRow.createCell(titles.length + i);
        cell.setCellValue(calendar);
        cell.setCellStyle(styles.get("header_date"));
        calendar.roll(Calendar.WEEK_OF_YEAR, true);
    }
    //freeze the first row
    sheet.createFreezePane(0, 1);

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

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

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

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

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

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

From source file:com.ebay.xcelite.Xcelite.java

License:Apache License

public Xcelite() {
    workbook = new XSSFWorkbook();
}

From source file:com.endro.belajar.controller.InvoiceProdukController.java

private void clickedbuttonExportDialog() {
    dialogExport.getButtonExport().addActionListener(new ActionListener() {
        @Override//  w  w w.  ja va  2  s . c  o  m
        public void actionPerformed(ActionEvent e) {
            try {
                LocalDate tanggalAwal = dialogExport.getTanggalAwalChooser().getDate().toInstant()
                        .atZone(ZoneId.systemDefault()).toLocalDate();
                LocalDate tanggalAkhir = dialogExport.getTanggalAkhirChooser().getDate().toInstant()
                        .atZone(ZoneId.systemDefault()).toLocalDate();

                List<InvoiceOrder> daftar = invoiceDao.findAllByTanggal(tanggalAwal, tanggalAkhir);
                processConvertExcel(daftar);
            } catch (SQLException | IOException ex) {
                Logger.getLogger(InvoiceProdukController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NullPointerException ex) {
                JOptionPane.showMessageDialog(dialogExport, "Form tanggal diisi dengan lengkap!");
            } finally {
                dialogExport.dispose();
                dialogExport = null;
            }
        }

        private void processConvertExcel(List<InvoiceOrder> daftarInvoice)
                throws FileNotFoundException, IOException {
            Integer returnVal = dialogExport.getChooserSaveFile().showOpenDialog(dialogExport);

            if (returnVal == dialogExport.getChooserSaveFile().APPROVE_OPTION) {
                XSSFWorkbook workbook = new XSSFWorkbook();
                XSSFSheet sheet = workbook.createSheet("Just Example");

                List<InvoiceOrder> list = daftarInvoice;

                Integer rowTable = 0;
                Integer cellTable = 0;
                CellStyle cellStyleTanggal = workbook.createCellStyle();
                CellStyle cellStyleHeader = workbook.createCellStyle();
                CellStyle cellStyleDouble = workbook.createCellStyle();

                CreationHelper createHelper = workbook.getCreationHelper();
                XSSFFont font = workbook.createFont();

                cellStyleTanggal.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
                cellStyleDouble.setDataFormat(
                        createHelper.createDataFormat().getFormat("[$Rp-421]#,##0.0000;-[$Rp-421]#,##0.0000"));
                font.setBold(true);
                cellStyleHeader.setFont(font);
                cellStyleHeader.setWrapText(true);
                //cellStyleHeader.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
                cellStyleHeader.setFillPattern(FillPatternType.DIAMONDS);
                for (InvoiceOrder order : list) {
                    Row row = sheet.createRow(rowTable);

                    if (rowTable == 0) {
                        sheet.setColumnWidth(0, 2000);
                        Cell cellHeader = row.createCell(0);
                        cellHeader.setCellValue("ID");
                        cellHeader.setCellStyle(cellStyleHeader);

                        sheet.setColumnWidth(1, 5000);
                        cellHeader = row.createCell(1);
                        cellHeader.setCellValue("Nomor Transaksi");
                        cellHeader.setCellStyle(cellStyleHeader);

                        sheet.setColumnWidth(2, 4000);
                        cellHeader = row.createCell(2);
                        cellHeader.setCellValue("Tanggal");
                        cellHeader.setCellStyle(cellStyleHeader);

                        sheet.setColumnWidth(3, 6000 * 3);
                        cellHeader = row.createCell(3);
                        cellHeader.setCellValue("Informasi Posting");
                        cellHeader.setCellStyle(cellStyleHeader);

                        sheet.setColumnWidth(4, 4850);
                        cellHeader = row.createCell(4);
                        cellHeader.setCellValue("Total Sebelum Diskon");
                        cellHeader.setCellStyle(cellStyleHeader);

                        sheet.setColumnWidth(5, 5000);
                        cellHeader = row.createCell(5);
                        cellHeader.setCellValue("Diskon");
                        cellHeader.setCellStyle(cellStyleHeader);

                        sheet.setColumnWidth(6, 4500);
                        cellHeader = row.createCell(6);
                        cellHeader.setCellValue("Total Setelah Diskon");
                        cellHeader.setCellStyle(cellStyleHeader);

                        sheet.setColumnWidth(7, 5000 * 2);
                        cellHeader = row.createCell(7);
                        cellHeader.setCellValue("Alamat Pengiriman");
                        cellHeader.setCellStyle(cellStyleHeader);
                    } else {
                        row.createCell(0).setCellValue((Integer) order.getPk());
                        row.createCell(1).setCellValue((String) order.getNomortransaksi());

                        Cell cellTanggal = row.createCell(2);
                        cellTanggal.setCellValue((Date) order.getTanggal());
                        cellTanggal.setCellStyle(cellStyleTanggal);

                        row.createCell(3).setCellValue((String) order.getInformasiposting());

                        Cell cellDouble = row.createCell(4);
                        cellDouble.setCellValue(order.getTotalbelumdiskon());
                        cellDouble.setCellStyle(cellStyleDouble);

                        cellDouble = row.createCell(5);
                        cellDouble.setCellValue(order.getDiskonfaktur());
                        cellDouble.setCellStyle(cellStyleDouble);

                        cellDouble = row.createCell(6);
                        cellDouble.setCellValue(order.getTotalsetelahdiskon());
                        cellDouble.setCellStyle(cellStyleDouble);

                        row.createCell(7).setCellValue((String) order.getAlamatpengiriman() == null ? "Null"
                                : order.getAlamatpengiriman());
                    }
                    rowTable++;
                }

                File file = dialogExport.getChooserSaveFile().getSelectedFile();

                FileOutputStream outputStream = new FileOutputStream(file + File.separator + "Penjualan.xlsx");
                workbook.write(outputStream);

                int pesan = JOptionPane.showConfirmDialog(dialogExport,
                        "Telah tersimpan di " + file + File.separator
                                + "Penjualan.xlsx \n Apakah anda ingin membuka file tersebut?",
                        "Notification", JOptionPane.OK_CANCEL_OPTION);
                if (pesan == JOptionPane.YES_OPTION) {
                    if ("Linux".equals(System.getProperty("os.name"))) {
                        String runPenjualan = "xdg-open " + file + File.separator + "Penjualan.xlsx";
                        Runtime.getRuntime().exec(runPenjualan);
                    } else if ("Windows".equals(System.getProperty("os.name"))) {
                        String runPenjualan = "excel.exe /r" + file + File.separator + "Penjualan.xlsx";
                        Runtime.getRuntime().exec(runPenjualan);
                    }
                }
            } else {
                dialogExport.getChooserSaveFile().cancelSelection();
            }
        }
    });
}