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

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

Introduction

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

Prototype

Sheet createSheet(String sheetname);

Source Link

Document

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

Usage

From source file:de.tudarmstadt.ukp.csniper.webapp.statistics.page.export.ExportExcelTask.java

License:Apache License

@Override
protected void run() {
    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("Summary");

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);/*from  ww  w  .  java2 s . c o m*/
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    contextProvider.setOutputPos(exportModel.includePos);

    outputFile = null;
    OutputStream os = null;
    try {
        List<AggregatedEvaluationResult> results = repository.listAggregatedResults(formModel.getCollections(),
                formModel.getTypes(), formModel.getUsers(), formModel.getUserThreshold(),
                formModel.getConfidenceThreshold());

        List<AdditionalColumn> ac = exportModel.additionalColumns;

        Collections.sort(results, new Comparator<AggregatedEvaluationResult>() {
            @Override
            public int compare(AggregatedEvaluationResult aO1, AggregatedEvaluationResult aO2) {
                String id1 = aO1.getItem().getCollectionId() + "|" + aO1.getItem().getDocumentId();
                String id2 = aO2.getItem().getCollectionId() + "|" + aO2.getItem().getDocumentId();
                return id1.compareTo(id2);
            }
        });

        // Write header row
        List<String> colIds = new ArrayList<String>(Arrays.asList("User", "Collection", "Document", "Begin",
                "End", "Left", "Unit", "Right", "Type", "Class", "Confidence", "Correct", "Wrong"));
        for (int i = 0; i < ac.size(); i++) {
            colIds.add(ac.get(i).getName());
        }
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < colIds.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(colIds.get(i));
        }

        // Write rest
        setTotal(results.size());
        int rowNum = 1;
        for (AggregatedEvaluationResult aer : results) {
            ResultFilter classification = aer.getClassification();
            if (formModel.getFilters().contains(classification)) {
                ItemContext context = contextProvider.getContext(aer.getItem(), exportModel.contextSize,
                        exportModel.contextSize);

                // only differentiate between users if additional columns are being exported
                Set<String> users;
                if (ac.isEmpty()) {
                    users = new HashSet<String>(Arrays.asList(""));
                } else {
                    users = aer.getUsers(false);
                }

                // output the AggregatedEvaluationResult for every user (because the additional
                // columns entries might differ)
                for (String user : users) {
                    Row row = sheet.createRow(rowNum);
                    row.createCell(0).setCellValue(user);
                    row.createCell(1).setCellValue(aer.getItem().getCollectionId());
                    row.createCell(2).setCellValue(aer.getItem().getDocumentId());
                    row.createCell(3).setCellValue(aer.getItem().getBeginOffset());
                    row.createCell(4).setCellValue(aer.getItem().getEndOffset());
                    row.createCell(5).setCellValue(context.getLeft());
                    row.createCell(6).setCellValue(context.getUnit());
                    row.createCell(7).setCellValue(context.getRight());
                    row.createCell(8).setCellValue(aer.getItem().getType());
                    row.createCell(9).setCellValue(classification.toString());
                    row.createCell(10).setCellValue(aer.getConfidence());
                    row.createCell(11).setCellValue(aer.getCorrect());
                    row.createCell(12).setCellValue(aer.getWrong());
                    for (int i = 0; i < ac.size(); i++) {
                        String cellValue = repository.getEvaluationResult(aer.getItem().getId(), user)
                                .getAdditionalColumns().get(ac.get(i));
                        if (cellValue == null) {
                            cellValue = "";
                        }
                        row.createCell(colIds.size() - ac.size() + i).setCellValue(cellValue);

                    }
                    rowNum++;
                }
            }

            // Make sure we do not get to 100% before we did the classification, because
            // otherwise ProgressBar.onFinish() will trigger!!!
            increment();
            if (isCancelled()) {
                break;
            }
        }

        outputFile = File.createTempFile("date", ".csv");
        os = new FileOutputStream(outputFile);
        wb.write(os);
    } catch (IOException e) {
        e.printStackTrace();
        error("Export failed: " + ExceptionUtils.getRootCauseMessage(e));
        cancel();
    } finally {
        IOUtils.closeQuietly(os);
        if (isCancelled()) {
            clean();
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.lab.reporting.FlexTable.java

License:Apache License

public StreamWriter getExcelWriter() {
    return new StreamWriter() {
        @Override//  w ww .j  a v  a2 s.c  om
        public void write(OutputStream aStream) throws Exception {
            String[] colIds = compact ? getCompactColumnIds(false) : getColumnIds();

            Workbook wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet("Summary");

            PrintSetup printSetup = sheet.getPrintSetup();
            printSetup.setLandscape(true);
            sheet.setFitToPage(true);
            sheet.setHorizontallyCenter(true);

            // Header row
            {
                Row row = sheet.createRow(0);
                Cell rowIdCell = row.createCell(0);
                rowIdCell.setCellValue("ID");

                int colNum = 1;
                for (String colId : colIds) {
                    Cell cell = row.createCell(colNum);
                    cell.setCellValue(colId);
                    colNum++;
                }
            }

            //  Body rows
            {
                int rowNum = 1;
                for (String rowId : getRowIds()) {
                    Row row = sheet.createRow(rowNum);
                    Cell rowIdCell = row.createCell(0);
                    rowIdCell.setCellValue(rowId);

                    int colNum = 1;
                    for (String colId : colIds) {
                        Cell cell = row.createCell(colNum);
                        String value = getValueAsString(rowId, colId);
                        try {
                            cell.setCellValue(Double.valueOf(value));
                        } catch (NumberFormatException e) {
                            cell.setCellValue(value);
                        }
                        colNum++;
                    }
                    rowNum++;
                }
            }

            wb.write(aStream);
        }
    };
}

From source file:demo.poi.BusinessPlan.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb = new HSSFWorkbook();

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

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

    // turn off gridlines
    sheet.setDisplayGridlines(false);//from  w ww.j  a  v a 2  s. com
    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.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++) {
            String str = data[i][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.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 = "target/businessplan.xls";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:demo.poi.LoanCalculator.java

License:Apache License

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

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else//from w  ww  . j  a va2  s  .c  o  m
        wb = new HSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);
    Sheet sheet = wb.createSheet("Loan Calculator");
    sheet.setPrintGridlines(false);
    sheet.setDisplayGridlines(false);

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    sheet.setColumnWidth(0, 3 * 256);
    sheet.setColumnWidth(1, 3 * 256);
    sheet.setColumnWidth(2, 11 * 256);
    sheet.setColumnWidth(3, 14 * 256);
    sheet.setColumnWidth(4, 14 * 256);
    sheet.setColumnWidth(5, 14 * 256);
    sheet.setColumnWidth(6, 14 * 256);

    createNames(wb);

    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(35);
    for (int i = 1; i <= 7; i++) {
        titleRow.createCell(i).setCellStyle(styles.get("title"));
    }
    Cell titleCell = titleRow.getCell(2);
    titleCell.setCellValue("Simple Loan Calculator");
    sheet.addMergedRegion(CellRangeAddress.valueOf("$C$1:$H$1"));

    Row row = sheet.createRow(2);
    Cell cell = row.createCell(4);
    cell.setCellValue("Enter values");
    cell.setCellStyle(styles.get("item_right"));

    row = sheet.createRow(3);
    cell = row.createCell(2);
    cell.setCellValue("Loan amount");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_$"));
    cell.setAsActiveCell();

    row = sheet.createRow(4);
    cell = row.createCell(2);
    cell.setCellValue("Annual interest rate");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_%"));

    row = sheet.createRow(5);
    cell = row.createCell(2);
    cell.setCellValue("Loan period in years");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_i"));

    row = sheet.createRow(6);
    cell = row.createCell(2);
    cell.setCellValue("Start date of loan");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_d"));

    row = sheet.createRow(8);
    cell = row.createCell(2);
    cell.setCellValue("Monthly payment");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Monthly_Payment,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    row = sheet.createRow(9);
    cell = row.createCell(2);
    cell.setCellValue("Number of payments");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Loan_Years*12,\"\")");
    cell.setCellStyle(styles.get("formula_i"));

    row = sheet.createRow(10);
    cell = row.createCell(2);
    cell.setCellValue("Total interest");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Total_Cost-Loan_Amount,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    row = sheet.createRow(11);
    cell = row.createCell(2);
    cell.setCellValue("Total cost of loan");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Monthly_Payment*Number_of_Payments,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    // Write the output to a file
    String file = "target/loan-calculator.xls";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:demo.poi.TimesheetDemo.java

License:Apache License

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

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else//from  w w w .  j  av a2s.c  o  m
        wb = new HSSFWorkbook();

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

    Sheet sheet = wb.createSheet("Timesheet");
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    // title row
    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(45);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue("Weekly Timesheet");
    titleCell.setCellStyle(styles.get("title"));
    sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$L$1"));

    // header row
    Row headerRow = sheet.createRow(1);
    headerRow.setHeightInPoints(40);
    Cell headerCell;
    for (int i = 0; i < titles.length; i++) {
        headerCell = headerRow.createCell(i);
        headerCell.setCellValue(titles[i]);
        headerCell.setCellStyle(styles.get("header"));
    }

    int rownum = 2;
    for (int i = 0; i < 10; i++) {
        Row row = sheet.createRow(rownum++);
        for (int j = 0; j < titles.length; j++) {
            Cell cell = row.createCell(j);
            if (j == 9) {
                // the 10th cell contains sum over week days, e.g.
                // SUM(C3:I3)
                String ref = "C" + rownum + ":I" + rownum;
                cell.setCellFormula("SUM(" + ref + ")");
                cell.setCellStyle(styles.get("formula"));
            } else if (j == 11) {
                cell.setCellFormula("J" + rownum + "-K" + rownum);
                cell.setCellStyle(styles.get("formula"));
            } else {
                cell.setCellStyle(styles.get("cell"));
            }
        }
    }

    // row with totals below
    Row sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(35);
    Cell cell;
    cell = sumRow.createCell(0);
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellValue("Total Hrs:");
    cell.setCellStyle(styles.get("formula"));

    for (int j = 2; j < 12; j++) {
        cell = sumRow.createCell(j);
        String ref = (char) ('A' + j) + "3:" + (char) ('A' + j) + "12";
        cell.setCellFormula("SUM(" + ref + ")");
        if (j >= 9)
            cell.setCellStyle(styles.get("formula_2"));
        else
            cell.setCellStyle(styles.get("formula"));
    }
    rownum++;
    sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(25);
    cell = sumRow.createCell(0);
    cell.setCellValue("Total Regular Hours");
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellFormula("L13");
    cell.setCellStyle(styles.get("formula_2"));
    sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(25);
    cell = sumRow.createCell(0);
    cell.setCellValue("Total Overtime Hours");
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellFormula("K13");
    cell.setCellStyle(styles.get("formula_2"));

    // set sample data
    for (int i = 0; i < sample_data.length; i++) {
        Row row = sheet.getRow(2 + i);
        for (int j = 0; j < sample_data[i].length; j++) {
            if (sample_data[i][j] == null)
                continue;

            if (sample_data[i][j] instanceof String) {
                row.getCell(j).setCellValue((String) sample_data[i][j]);
            } else {
                row.getCell(j).setCellValue((Double) sample_data[i][j]);
            }
        }
    }

    // finally set column widths, the width is measured in units of 1/256th
    // of a character width
    sheet.setColumnWidth(0, 30 * 256); // 30 characters wide
    for (int i = 2; i < 9; i++) {
        sheet.setColumnWidth(i, 6 * 256); // 6 characters wide
    }
    sheet.setColumnWidth(10, 10 * 256); // 10 characters wide

    // Write the output to a file
    String file = "target/timesheet.xls";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:Demos.CalendarDemo.java

License:Apache License

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

    Calendar calendar = Calendar.getInstance();
    boolean xlsx = true;
    for (int i = 0; i < args.length; i++) {
        if (args[i].charAt(0) == '-') {
            xlsx = args[i].equals("-xlsx");
        } else {//from w  w  w .j a v  a 2 s .com
            calendar.set(Calendar.YEAR, Integer.parseInt(args[i]));
        }
    }
    int year = calendar.get(Calendar.YEAR);

    Workbook wb = xlsx ? new XSSFWorkbook() : new HSSFWorkbook();

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

    for (int month = 0; month < 12; month++) {
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        // create a sheet for each month
        Sheet sheet = wb.createSheet(months[month]);

        // 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(80);
        Cell titleCell = headerRow.createCell(0);
        titleCell.setCellValue(months[month] + " " + year);
        titleCell.setCellStyle(styles.get("title"));
        sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));

        // header with month titles
        Row monthRow = sheet.createRow(1);
        for (int i = 0; i < days.length; i++) {
            // set column widths, the width is measured in units of 1/256th
            // of a character width
            sheet.setColumnWidth(i * 2, 5 * 256); // the column is 5
            // characters wide
            sheet.setColumnWidth(i * 2 + 1, 13 * 256); // the column is 13
            // characters wide
            sheet.addMergedRegion(new CellRangeAddress(1, 1, i * 2, i * 2 + 1));
            Cell monthCell = monthRow.createCell(i * 2);
            monthCell.setCellValue(days[i]);
            monthCell.setCellStyle(styles.get("month"));
        }

        int cnt = 1, day = 1;
        int rownum = 2;
        for (int j = 0; j < 6; j++) {
            Row row = sheet.createRow(rownum++);
            row.setHeightInPoints(100);
            for (int i = 0; i < days.length; i++) {
                Cell dayCell_1 = row.createCell(i * 2);
                Cell dayCell_2 = row.createCell(i * 2 + 1);

                int day_of_week = calendar.get(Calendar.DAY_OF_WEEK);
                if (cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) {
                    dayCell_1.setCellValue(day);
                    calendar.set(Calendar.DAY_OF_MONTH, ++day);

                    if (i == 0 || i == days.length - 1) {
                        dayCell_1.setCellStyle(styles.get("weekend_left"));
                        dayCell_2.setCellStyle(styles.get("weekend_right"));
                    } else {
                        dayCell_1.setCellStyle(styles.get("workday_left"));
                        dayCell_2.setCellStyle(styles.get("workday_right"));
                    }
                } else {
                    dayCell_1.setCellStyle(styles.get("grey_left"));
                    dayCell_2.setCellStyle(styles.get("grey_right"));
                }
                cnt++;
            }
            if (calendar.get(Calendar.MONTH) > month)
                break;
        }
    }

    // Write the output to a file
    String file = "C:\\Users\\BaldiniHP\\Desktop\\calendar.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:dijkstrafib.DijkstraMain.java

public static void exportData(String fileName, String tabName, double[][] data)
        throws FileNotFoundException, IOException {
    //Create new workbook and tab
    Workbook wb = new HSSFWorkbook();
    FileOutputStream fileOut = new FileOutputStream(fileName);
    Sheet sheet = wb.createSheet(tabName);

    //Create 2D Cell Array
    Row[] row = new Row[data.length];
    Cell[][] cell = new Cell[row.length][];

    //Define and Assign Cell Data from Given
    for (int i = 0; i < row.length; i++) {
        row[i] = sheet.createRow(i);/* www.j  a va2 s  .  c  o m*/
        cell[i] = new Cell[data[i].length];

        for (int j = 0; j < cell[i].length; j++) {
            cell[i][j] = row[i].createCell(j);
            cell[i][j].setCellValue(data[i][j]);
        }
    }

    //Export Data
    wb.write(fileOut);
    fileOut.close();
}

From source file:dylemator.UserList.java

private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
    if (this.filenameCombo.getSelectedIndex() == 0)
        return;/*from   w  w  w  .j  a v a2s  .  c  o m*/
    String sheetName = (String) this.filenameCombo.getSelectedItem();
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet(sheetName);
    Row headerRow = sheet.createRow(0);
    String[] headers = exportData.get(0);
    int numOfColumns = headers.length;
    for (int i = 0; i < numOfColumns; i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellValue(headers[i]);
    }

    int rowCount = exportData.size();
    for (int rownum = 1; rownum < rowCount; rownum++) {
        Row row = sheet.createRow(rownum);
        String[] values = exportData.get(rownum);
        for (int i = 0; i < numOfColumns; i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(values[i]);
        }
    }

    String defaultFilename = "Export.xlsx";
    JFileChooser f = new JFileChooser(System.getProperty("user.dir"));
    f.setSelectedFile(new File(defaultFilename));
    f.setDialogTitle("Wybierz nazw dla pliku eksportu");
    f.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileFilter ff = new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.getName().endsWith(".xlsx"))
                return true;
            return false;
        }

        @Override
        public String getDescription() {
            return "";
        }
    };
    f.setFileFilter(ff);

    File file = null;
    int save = f.showSaveDialog(this);
    if (save == JFileChooser.APPROVE_OPTION)
        file = f.getSelectedFile();
    else
        return;

    FileOutputStream out;
    try {
        out = new FileOutputStream(file);
        wb.write(out);
        out.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(UserList.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UserList.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:dylemator.UserResultList.java

private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
    if (this.filenameCombo.getSelectedIndex() == 0)
        return;/*from www  .j  a v  a2s  .c o m*/
    String sheetName = (String) this.filenameCombo.getSelectedItem();
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet(sheetName);
    Row headerRow = sheet.createRow(0);
    String[] headers = exportData.get(0);
    int numOfColumns = headers.length;
    for (int i = 0, j = 0; i < numOfColumns; i++) {
        if (i == 1 || i == 2 || i == 3) // opuszcz. date, imie, nazwisko
            continue;
        Cell cell = headerRow.createCell(j++);
        cell.setCellValue(headers[i]);
    }

    int rowCount = exportData.size();
    for (int rownum = 1; rownum < rowCount; rownum++) {
        Row row = sheet.createRow(rownum);
        String[] values = exportData.get(rownum);
        for (int i = 0, j = 0; i < numOfColumns; i++) {
            if (i == 1 || i == 2 || i == 3) // opuszcz. date, imie, nazwisko
                continue;
            Cell cell = row.createCell(j++);
            cell.setCellValue(values[i]);
        }
    }

    String defaultFilename = "Export.xlsx";
    JFileChooser f = new JFileChooser(System.getProperty("user.dir"));
    f.setSelectedFile(new File(defaultFilename));
    f.setDialogTitle("Wybierz nazw dla pliku eksportu");
    f.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileFilter ff = new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.getName().endsWith(".xlsx"))
                return true;
            return false;
        }

        @Override
        public String getDescription() {
            return "";
        }
    };
    f.setFileFilter(ff);

    File file = null;
    int save = f.showSaveDialog(this);
    if (save == JFileChooser.APPROVE_OPTION)
        file = f.getSelectedFile();
    else
        return;

    FileOutputStream out;
    try {
        out = new FileOutputStream(file);
        wb.write(out);
        out.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(UserResultList.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UserResultList.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ec.tss.sa.output.XSSFHelper.java

License:EUPL

public static Sheet addSheet(Workbook curBook, String sheetName, String[] headers0, String[] headers1,
        TsDataTable table, boolean verticalOrientation) {
    Sheet sheet = curBook.createSheet(sheetName);
    Row currentRow = null;// w  w w. j  a  v a 2s  . com
    Cell currentCell = null;

    if (verticalOrientation) {
        //headers0
        int rowNum = 0;
        currentRow = sheet.createRow(rowNum);
        for (int cellNum = 0; cellNum < headers0.length; cellNum++) {
            currentCell = currentRow.createCell(cellNum + 1, XSSFCell.CELL_TYPE_STRING);
            currentCell.setCellValue(headers0[cellNum]);
        }
        //headers1
        rowNum++;
        currentRow = sheet.createRow(rowNum);
        for (int cellNum = 0; cellNum < headers1.length; cellNum++) {
            currentCell = currentRow.createCell(1 + cellNum, XSSFCell.CELL_TYPE_STRING);
            currentCell.setCellValue(headers1[cellNum]);
        }
        //columnvalues & data
        for (int i = 0; i < table.getDomain().getLength(); i++) {
            ++rowNum;
            currentRow = sheet.createRow(rowNum);
            int cellNum = 0;
            currentCell = currentRow.createCell(cellNum);
            currentCell.setCellValue(table.getDomain().get(i).firstday().toString());
            for (int j = 0; j < table.getSeriesCount(); j++) {
                cellNum++;
                currentCell = currentRow.createCell(cellNum);
                TsDataTableInfo info = table.getDataInfo(i, j);
                if (info == TsDataTableInfo.Valid) {
                    currentCell.setCellValue(table.getData(i, j));
                } else {
                    currentCell.setCellValue("");
                }
            }
        }
    } else {
        // headers0
        int rowNum = 0;
        int nbComponents = headers1.length / countNbSeries(headers0);
        int currentData = 0;
        for (String h : headers0) {
            if (!h.isEmpty()) {
                currentRow = sheet.createRow(rowNum);
                currentCell = currentRow.createCell(1, XSSFCell.CELL_TYPE_STRING);
                currentCell.setCellValue(h);

                // Periods
                rowNum++;
                currentRow = sheet.createRow(rowNum);
                for (int i = 0; i < table.getDomain().getLength(); i++) {
                    currentCell = currentRow.createCell(i + 1);
                    currentCell.setCellValue(table.getDomain().get(i).firstday().toString());
                }

                // Components + Data
                for (int i = currentData; i < currentData + nbComponents; i++) {
                    currentRow = sheet.createRow(++rowNum);
                    currentCell = currentRow.createCell(0, XSSFCell.CELL_TYPE_STRING);
                    currentCell.setCellValue(headers1[i]);
                    for (int j = 0; j < table.getDomain().getLength(); j++) {
                        currentCell = currentRow.createCell(j + 1);
                        TsDataTableInfo info = table.getDataInfo(j, i);
                        if (info == TsDataTableInfo.Valid) {
                            currentCell.setCellValue(table.getData(j, i));
                        } else {
                            currentCell.setCellValue("");
                        }
                    }
                }

                rowNum += 2;
            }
            currentData++;
        }

    }

    return sheet;
}