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

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

Introduction

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

Prototype

public HSSFWorkbook() 

Source Link

Document

Creates new HSSFWorkbook from scratch (start here!)

Usage

From source file:com.clonescriptscrapper.excelfile.GenerateCsvFile.java

public static void excel() throws FileNotFoundException, IOException {

    HSSFWorkbook hwb = new HSSFWorkbook();
    HSSFSheet sheet = hwb.createSheet("Monster Details");
    HSSFRow rowhead = sheet.createRow((int) 0);
    rowhead.createCell((int) 0).setCellValue("S.No.");
    rowhead.createCell((int) 1).setCellValue("CATEGORY_DATA_ID");
    rowhead.createCell((int) 2).setCellValue("CATEGORY_ID");
    rowhead.createCell((int) 3).setCellValue("TITLE");
    rowhead.createCell((int) 4).setCellValue("NAME");
    rowhead.createCell((int) 5).setCellValue("CLICKS");
    rowhead.createCell((int) 6).setCellValue("ADDED_ON");
    rowhead.createCell((int) 7).setCellValue("PAGE_RANK");
    rowhead.createCell((int) 8).setCellValue("DESCRIPTION");
    rowhead.createCell((int) 9).setCellValue("DEMO_URL");
    rowhead.createCell((int) 10).setCellValue("CATEGORY_ID");
    rowhead.createCell((int) 11).setCellValue("CATEGORY_NAME");
    rowhead.createCell((int) 12).setCellValue("CATEGORY_URL");
    rowhead.createCell((int) 13).setCellValue("ISCRAWLED");

    try {//w  ww  .  ja v a 2  s.  c  o m
        Class.forName("com.mysql.jdbc.Driver");
        java.sql.Connection con = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/clonescriptdirectorydb", "root", "");
        String sql = "SELECT * FROM `categories_data`,categories where categories_data.CATEGORY_ID= categories .CATEGORY_ID;";
        java.sql.PreparedStatement ps = con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        int k = 0;
        while (rs.next()) {

            HSSFRow row = sheet.createRow((int) k + 2);
            try {
                row.createCell((int) 0).setCellValue(k + 1);
            } catch (Exception sd) {
            }
            try {
                row.createCell((int) 1).setCellValue(rs.getString("CATEGORY_DATA_ID") + "");
            } catch (Exception sd) {
            }

            try {
                row.createCell((int) 2).setCellValue(rs.getString("CATEGORY_ID") + "");
            } catch (Exception sd) {
            }

            try {
                row.createCell((int) 3).setCellValue(rs.getString("TITLE") + "");
            } catch (Exception sd) {
            }

            try {
                row.createCell((int) 4).setCellValue(rs.getString("NAME") + "");
            } catch (Exception sd) {
            }

            try {
                row.createCell((int) 5).setCellValue(rs.getString("CLICKS") + "");
            } catch (Exception sd) {
            }

            try {
                row.createCell((int) 6).setCellValue(rs.getString("ADDED_ON") + "");
            } catch (Exception sd) {
            }

            try {
                row.createCell((int) 7).setCellValue(rs.getString("PAGE_RANK") + "");
            } catch (Exception sd) {
            }

            try {
                row.createCell((int) 8).setCellValue(rs.getString("DESCRIPTION") + "");
            } catch (Exception sd) {
            }

            try {
                row.createCell((int) 9).setCellValue(rs.getString("DEMO_URL") + "");
            } catch (Exception sd) {
            }
            try {
                row.createCell((int) 10).setCellValue(rs.getString("CATEGORY_ID") + "");
            } catch (Exception sd) {
            }
            try {
                row.createCell((int) 11).setCellValue(rs.getString("CATEGORY_NAME") + "");
            } catch (Exception sd) {
            }

            try {
                row.createCell((int) 12).setCellValue(rs.getString("CATEGORY_URL") + "");
            } catch (Exception sd) {
            }

            try {
                row.createCell((int) 13).setCellValue(rs.getString("ISCRAWLED") + "");
            } catch (Exception sd) {
            }

            k++;
        }

        try {

            String filename = "data.csv";
            System.out.println("Directory is created!");
            FileOutputStream fileOut = new FileOutputStream(filename);
            hwb.write(fileOut);
            fileOut.close();
            System.out.println("Your excel file has been generated!");
        } catch (IOException iOException) {
        }

    } catch (Exception aaa) {
    }

}

From source file:com.commander4j.util.JExcel.java

License:Open Source License

public void exportToExcel(String filename, ResultSet rs) {
    try {/*from   w  w w  .  ja  v a  2 s.  c o m*/

        ResultSetMetaData rsmd = rs.getMetaData();
        int numberOfColumns = rsmd.getColumnCount();
        int columnType = 0;
        String columnTypeName = "";
        int recordNumber = 0;
        int passwordCol = -1;

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();

        HSSFCellStyle cellStyle_varchar = workbook.createCellStyle();
        cellStyle_varchar.setAlignment(HorizontalAlignment.LEFT);

        HSSFCellStyle cellStyle_nvarchar = workbook.createCellStyle();
        cellStyle_nvarchar.setAlignment(HorizontalAlignment.LEFT);

        HSSFCellStyle cellStyle_varchar2 = workbook.createCellStyle();
        cellStyle_varchar2.setAlignment(HorizontalAlignment.LEFT);

        HSSFCellStyle cellStyle_title = workbook.createCellStyle();
        cellStyle_title.setAlignment(HorizontalAlignment.CENTER);

        HSSFCellStyle cellStyle_char = workbook.createCellStyle();
        cellStyle_char.setAlignment(HorizontalAlignment.LEFT);

        HSSFCellStyle cellStyle_date = workbook.createCellStyle();
        cellStyle_date.setAlignment(HorizontalAlignment.CENTER);
        cellStyle_date.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

        HSSFCellStyle cellStyle_timestamp = workbook.createCellStyle();
        cellStyle_timestamp.setAlignment(HorizontalAlignment.CENTER);
        cellStyle_timestamp.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

        HSSFCellStyle cellStyle_decimal = workbook.createCellStyle();
        cellStyle_decimal.setAlignment(HorizontalAlignment.RIGHT);

        HSSFFont font_title = workbook.createFont();
        font_title.setColor((short) 0xc);
        font_title.setBold(true);
        ;
        font_title.setItalic(true);
        font_title.setUnderline(HSSFFont.U_DOUBLE);
        cellStyle_title.setFont(font_title);

        HSSFCell cell;
        HSSFRow row;

        // rs.beforeFirst();

        while (rs.next()) {
            recordNumber++;

            if (recordNumber == 1) {
                row = sheet.createRow((int) 0);
                for (int column = 1; column <= numberOfColumns; column++) {
                    cell = row.createCell((int) (column - 1));
                    String columnName = rsmd.getColumnLabel(column);
                    columnName = columnName.replace("_", " ");
                    columnName = JUtility.capitalize(columnName);
                    cell.setCellStyle(cellStyle_title);
                    cell.setCellValue(columnName);
                    if (columnName.equals("Password")) {
                        passwordCol = column;
                    }
                }
            }

            row = sheet.createRow((int) recordNumber);

            for (int column = 1; column <= numberOfColumns; column++) {

                columnType = rsmd.getColumnType(column);
                columnTypeName = rsmd.getColumnTypeName(column);

                cell = row.createCell((int) (column - 1));

                try {
                    switch (columnType) {
                    case java.sql.Types.NVARCHAR:
                        HSSFRichTextString rtf_nvarchar;
                        if (column == passwordCol) {
                            rtf_nvarchar = new HSSFRichTextString("*****");
                        } else {
                            rtf_nvarchar = new HSSFRichTextString(rs.getString(column));
                        }

                        cell.setCellStyle(cellStyle_nvarchar);
                        cell.setCellValue(rtf_nvarchar);
                        break;
                    case java.sql.Types.VARCHAR:
                        HSSFRichTextString rtf_varchar;
                        if (column == passwordCol) {
                            rtf_varchar = new HSSFRichTextString("*****");
                        } else {
                            rtf_varchar = new HSSFRichTextString(rs.getString(column));
                        }

                        cell.setCellStyle(cellStyle_varchar);
                        cell.setCellValue(rtf_varchar);
                        break;
                    case java.sql.Types.CHAR:
                        HSSFRichTextString rtf_char = new HSSFRichTextString(rs.getString(column));
                        cell.setCellStyle(cellStyle_char);
                        cell.setCellValue(rtf_char);
                        break;
                    case java.sql.Types.DATE:
                        try {
                            cell.setCellValue(rs.getTimestamp(column));
                            cell.setCellStyle(cellStyle_date);
                        } catch (Exception ex) {

                        }
                        break;
                    case java.sql.Types.TIMESTAMP:
                        try {
                            cell.setCellValue(rs.getTimestamp(column));
                            cell.setCellStyle(cellStyle_timestamp);
                        } catch (Exception ex) {

                        }
                        break;
                    case java.sql.Types.DECIMAL:
                        HSSFRichTextString rtf_decimal = new HSSFRichTextString(
                                rs.getBigDecimal(column).toString());
                        cell.setCellStyle(cellStyle_decimal);
                        cell.setCellValue(rtf_decimal);
                        break;
                    case java.sql.Types.NUMERIC:
                        HSSFRichTextString rtf_decimaln = new HSSFRichTextString(
                                rs.getBigDecimal(column).toString());
                        cell.setCellStyle(cellStyle_decimal);
                        cell.setCellValue(rtf_decimaln);
                        break;
                    case java.sql.Types.BIGINT:
                        HSSFRichTextString rtf_bigint = new HSSFRichTextString(
                                rs.getBigDecimal(column).toString());
                        cell.setCellStyle(cellStyle_decimal);
                        cell.setCellValue(rtf_bigint);
                        break;
                    case java.sql.Types.INTEGER:
                        HSSFRichTextString rtf_int = new HSSFRichTextString(String.valueOf(rs.getInt(column)));
                        cell.setCellStyle(cellStyle_decimal);
                        cell.setCellValue(rtf_int);
                        break;
                    case java.sql.Types.FLOAT:
                        HSSFRichTextString rtf_float = new HSSFRichTextString(
                                String.valueOf(rs.getFloat(column)));
                        cell.setCellStyle(cellStyle_decimal);
                        cell.setCellValue(rtf_float);
                        break;
                    case java.sql.Types.DOUBLE:
                        HSSFRichTextString rtf_double = new HSSFRichTextString(
                                String.valueOf(rs.getDouble(column)));
                        cell.setCellStyle(cellStyle_decimal);
                        cell.setCellValue(rtf_double);
                        break;
                    default:
                        cell.setCellValue(new HSSFRichTextString(columnTypeName));
                        break;
                    }
                } catch (Exception ex) {
                    String errormessage = ex.getLocalizedMessage();
                    HSSFRichTextString rtf_exception = new HSSFRichTextString(errormessage);
                    cell.setCellStyle(cellStyle_varchar);
                    cell.setCellValue(rtf_exception);
                    break;
                }
            }

            if (recordNumber == 65535) {
                break;
            }
        }

        for (int column = 1; column <= numberOfColumns; column++) {
            sheet.autoSizeColumn((int) (column - 1));
        }

        if (recordNumber > 0) {
            try {
                FileOutputStream fileOut = new FileOutputStream(filename.toLowerCase());
                workbook.write(fileOut);
                fileOut.close();
            } catch (Exception ex) {
                setErrorMessage(ex.getMessage());
            }
        }

        try {
            workbook.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (SQLException e) {
        setErrorMessage(e.getMessage());
    }
}

From source file:com.company.et.service.XlsService.java

public static void generateFile(List<TreeItem<Task>> root, List<ArrayList<ArrayList<Double>>> waitingParts,
        ObservableList<Professor> professors) throws FileNotFoundException, IOException {
    FileOutputStream out = new FileOutputStream(filename);
    Workbook wb = new HSSFWorkbook();

    for (int k = 0; k < professors.size(); k++) {

        Sheet s = wb.createSheet(professors.get(k).getFio());

        Row rowFirst = s.createRow(0);/*from w  w  w.j av a  2s. c  o  m*/

        createConstStringCells(wb, s, "??", rowFirst, 0, 0, 1, 0, 0);
        createConstStringCells(wb, s, "?? ", rowFirst, 1, 0, 0, 1, 3);
        createConstStringCells(wb, s, "? ", rowFirst, 4, 0, 0, 4, 6);
        createConstStringCells(wb, s, "?? ", rowFirst, 7, 0, 0, 7, 9);
        createConstStringCells(wb, s, "?? ", rowFirst, 10, 0, 0, 10, 12);
        createConstStringCells(wb, s, "?? ", rowFirst, 13, 0, 0, 13, 15);

        Row rowSecond = s.createRow(1);
        for (int i = 0, j = 1; i < 5; i++, j += 3) {
            createConstStringCells(wb, s, "", rowSecond, j, 0, 0, 0, 0);
            createConstStringCells(wb, s, "", rowSecond, j + 1, 0, 0, 0, 0);
            createConstStringCells(wb, s, "", rowSecond, j + 2, 0, 0, 0, 0);
        }

        for (int i = 1; i < 16; i++) {
            Row row = s.createRow(i + 1);
            for (int j = 0; j < root.get(k).getChildren().size(); j++) {
                createCellOfDouble(wb, s, row, j * 3 + 2,
                        root.get(k).getChildren().get(j).getValue().getCapacities().get(i));
                createCellOfDouble(wb, s, row, j * 3 + 1, waitingParts.get(k).get(j).get(i));
                createReserveCell(wb, s, row, (j + 1) * 3);

            }
            createMonthCell(wb, s, row, DoubleCapacities.getDoubleCapacitiesByIndex(i).toString());
            createFullTasksActualCell(wb, s, row, root.get(k).getChildren().size() * 3 + 1);
            createFullTasksCell(wb, s, row, root.get(k).getChildren().size() * 3 + 2);
            createFullTasksReserveCell(wb, s, row, (root.get(k).getChildren().size() + 1) * 3);

        }
    }
    FormulaEvaluator formulaEval = wb.getCreationHelper().createFormulaEvaluator();
    //all year report
    Sheet s = wb.createSheet("?");
    Row rowFirst = s.createRow(0);
    Row rowSecond = s.createRow(1);
    createConstStringCells(wb, s, "/", rowFirst, 0, 0, 1, 0, 0);
    createConstStringCells(wb, s, "", rowFirst, 1, 0, 1, 1, 1);
    createConstStringCells(wb, s, "?", rowFirst, 2, 0, 1, 2, 2);
    createConstStringCells(wb, s, ". .", rowFirst, 3, 0, 1, 3, 3);
    for (int i = 1; i < 16; i++) {
        createConstStringCells(wb, s, DoubleCapacities.getDoubleCapacitiesByIndex(i).toString(), rowFirst,
                (i * 3) + 1, 0, 0, (i * 3) + 1, (i * 3) + 3);
        createConstStringCells(wb, s, "", rowSecond, (i * 3) + 1, 1, 1, (i * 3) + 1, (i * 3) + 1);
        createConstStringCells(wb, s, "", rowSecond, (i * 3) + 2, 1, 1, (i * 3) + 2, (i * 3) + 2);
        createConstStringCells(wb, s, "", rowSecond, (i * 3) + 3, 1, 1, (i * 3) + 3, (i * 3) + 3);
    }
    for (int i = 0; i < professors.size(); i++) {
        Row row = s.createRow(i + 2);
        createConstStringCells(wb, s, Integer.toString(i + 1), row, 0, i + 2, i + 2, 0, 0);
        createConstStringCells(wb, s, professors.get(i).getFio(), row, 1, i + 2, i + 2, 1, 1);
        createConstStringCells(wb, s, professors.get(i).getRate().toString(), row, 3, i + 2, i + 2, 3, 3);
        for (int j = 1; j < 16; j++) {
            createConstStringCells(wb, s,
                    formulaEval.evaluate(wb.getSheet(professors.get(i).getFio()).getRow(j + 1).getCell(13))
                            .formatAsString(),
                    row, (j * 3) + 1, i + 2, i + 2, (j * 3) + 1, (j * 3) + 1);
            createConstStringCells(wb, s,
                    formulaEval.evaluate(wb.getSheet(professors.get(i).getFio()).getRow(j + 1).getCell(14))
                            .formatAsString(),
                    row, (j * 3) + 2, i + 2, i + 2, (j * 3) + 2, (j * 3) + 2);
            createConstStringCells(wb, s,
                    formulaEval.evaluate(wb.getSheet(professors.get(i).getFio()).getRow(j + 1).getCell(15))
                            .formatAsString(),
                    row, (j * 3) + 3, i + 2, i + 2, (j * 3) + 3, (j * 3) + 3);
        }
    }
    wb.write(out);

    out.close();

}

From source file:com.company.et.service.XlsService.java

public static void createReportForMonthForOnePerson(int numOfMonth, Professor professor,
        ArrayList<ArrayList<Double>> waitingParts, TreeItem<Task> root)
        throws FileNotFoundException, IOException {

    FileOutputStream out = new FileOutputStream(filename);
    Workbook wb = new HSSFWorkbook();
    Sheet s = wb.createSheet(professor.getFio());
    createReportForMonth(wb, s, numOfMonth, professor, waitingParts, root);
    wb.write(out);/*from   w w w  .java2 s .  co m*/
    out.close();
}

From source file:com.company.et.service.XlsService.java

public static void createReportForMonthForManyPerson(int numOfMonth, List<Professor> professors,
        ArrayList<ArrayList<ArrayList<Double>>> waitingParts, List<TreeItem<Task>> root)
        throws FileNotFoundException, IOException {

    FileOutputStream out = new FileOutputStream(filename);
    Workbook wb = new HSSFWorkbook();
    for (int i = 0; i < professors.size(); i++) {
        Sheet s = wb.createSheet(professors.get(i).getFio());
        createReportForMonth(wb, s, numOfMonth, professors.get(i), waitingParts.get(i), root.get(i));
    }//from www. ja  v a  2  s.co  m
    wb.write(out);
    out.close();
}

From source file:com.compomics.pepshell.controllers.dataexport.DataExport.java

License:Apache License

public void excelProteinExport(JList listOfProteins, File saveLocation)
        throws FileNotFoundException, IOException {
    Workbook workBook = new HSSFWorkbook();
    ExcelExport.exportProteinToExcelWorkBook(listOfProteins, workBook);
    writeFileToDisk(workBook, saveLocation);
}

From source file:com.controller.DownloadController.java

private void downloadCourseSpreadsheet(HttpServletRequest request, HttpServletResponse response) {

    Workbook workbook = new HSSFWorkbook();
    Sheet sheet = workbook.createSheet("Course Table");
    Row row = sheet.createRow(0);/* w  w w .  j  av  a  2  s. c  om*/
    row.createCell(2).setCellValue("Currently Course Enrollment Table");
    row = sheet.createRow(2);
    row.createCell(0).setCellValue("Number");
    row.createCell(1).setCellValue("Name");
    row.createCell(2).setCellValue("Room");
    row.createCell(3).setCellValue("Instructor");
    row.createCell(4).setCellValue("Days&Time");
    row.createCell(5).setCellValue("Credit");
    row.createCell(6).setCellValue("Registration Time");

    HttpSession session = request.getSession();
    List<CourseRegistration> enrolled = (List<CourseRegistration>) session.getAttribute("enrolled");

    int i = 4;
    for (CourseRegistration cr : enrolled) {
        row = sheet.createRow(i);
        row.createCell(0).setCellValue(cr.getCourse().getCourseNum());
        row.createCell(1).setCellValue(cr.getCourse().getName());
        row.createCell(2).setCellValue(cr.getCourse().getRoom());
        row.createCell(3).setCellValue(cr.getCourse().getInstructor());
        row.createCell(4).setCellValue(cr.getCourse().getDt());
        row.createCell(5).setCellValue(cr.getCourse().getCredit() - '0');
        row.createCell(6).setCellValue(cr.getCourseRegisterationDateDefaultFormat());
        i++;
    }

    response.setHeader("content-disposition", "attachment; filename=CourseEnrollment.xls");
    response.setHeader("cache-control", "no-cache");

    try (OutputStream out = response.getOutputStream()) {
        workbook.write(out);
    } catch (IOException ex) {
        System.out.println(ex.getStackTrace());
    }
}

From source file:com.crunchify.jsp.servlet.HSSFCreate.java

/**
 * Processes requests for both HTTP GET and POST methods.
 *
 * @param request servlet request/*from ww w. jav a  2s.co  m*/
 * @param response servlet response
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    DepartamentoDAO d = new DepartamentoDAO();

    response.setContentType("application/vnd.ms-excel");
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("new sheet");

    Map<String, Object[]> data = new HashMap<String, Object[]>();

    data.put("1", new Object[] { "Emp No.", "Name" });
    for (int i = 0; i < d.findAll().size(); i++) {
        data.put("2", new Object[] { d.findAll().get(i).getNom_departamento(),
                d.findAll().get(i).getNom_departamento() });
    }

    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 Date) {
                cell.setCellValue((Date) obj);
            } else if (obj instanceof Boolean) {
                cell.setCellValue((Boolean) obj);
            } else if (obj instanceof String) {
                cell.setCellValue((String) obj);
            } else if (obj instanceof Double) {
                cell.setCellValue((Double) obj);
            }
        }
    }

    // Write the output 
    OutputStream out = response.getOutputStream();
    wb.write(out);
    out.close();
}

From source file:com.daphne.es.showcase.excel.service.ExcelDataService.java

License:Apache License

/**
 * workbook/*from   w  w w .  j a  v a2  s. com*/
 * 1?vbs ?
 * 2?c#??
 * ? ????office 2007 ?
 * @param user
 * @param contextRootPath
 * @param searchable
 */
@Async
public void exportExcel2003WithOneSheetPerWorkBook(final User user, final String contextRootPath,
        final Searchable searchable) {
    int workbookCount = 0;
    List<String> workbookFileNames = new ArrayList<String>();
    int perSheetRows = 60000; //?sheet 6w?
    int totalRows = 0;
    String extension = "xls";

    int pageSize = 1000;
    Long maxId = 0L;

    BufferedOutputStream out = null;
    try {
        long beginTime = System.currentTimeMillis();

        while (true) {
            workbookCount++;
            String fileName = generateFilename(user, contextRootPath, workbookCount, extension);
            workbookFileNames.add(fileName);
            File file = new File(fileName);

            HSSFWorkbook wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet();
            Row headerRow = sheet.createRow(0);
            Cell idHeaderCell = headerRow.createCell(0);
            idHeaderCell.setCellValue("?");
            Cell contentHeaderCell = headerRow.createCell(1);
            contentHeaderCell.setCellValue("");

            totalRows = 1;

            Page<ExcelData> page = null;

            do {
                searchable.setPage(0, pageSize);
                //
                if (!searchable.containsSearchKey("id_in")) {
                    searchable.addSearchFilter("id", SearchOperator.gt, maxId);
                }
                page = findAll(searchable);

                for (ExcelData data : page.getContent()) {
                    Row row = sheet.createRow(totalRows);
                    Cell idCell = row.createCell(0);
                    idCell.setCellValue(data.getId());
                    Cell contentCell = row.createCell(1);
                    contentCell.setCellValue(data.getContent());
                    maxId = Math.max(maxId, data.getId());
                    totalRows++;
                }
                //clear entity manager
                RepositoryHelper.clear();
            } while (page.hasNext() && totalRows <= perSheetRows);

            out = new BufferedOutputStream(new FileOutputStream(file));
            wb.write(out);

            IOUtils.closeQuietly(out);

            if (!page.hasNext()) {
                break;
            }
        }

        String fileName = workbookFileNames.get(0);
        if (workbookCount > 1 || needCompress(new File(fileName))) {
            fileName = fileName.substring(0, fileName.lastIndexOf("_")) + ".zip";
            //
            compressAndDeleteOriginal(fileName, workbookFileNames.toArray(new String[0]));
        } else {
            String newFileName = fileName.substring(0, fileName.lastIndexOf("_")) + "." + extension;
            FileUtils.moveFile(new File(fileName), new File(newFileName));
            fileName = newFileName;
        }

        long endTime = System.currentTimeMillis();

        Map<String, Object> context = Maps.newHashMap();
        context.put("seconds", (endTime - beginTime) / 1000);
        context.put("url", fileName.replace(contextRootPath, ""));
        notificationApi.notify(user.getId(), "excelExportSuccess", context);
    } catch (Exception e) {
        e.printStackTrace();
        //
        IOUtils.closeQuietly(out);
        log.error("excel export error", e);
        Map<String, Object> context = Maps.newHashMap();
        context.put("error", e.getMessage());
        notificationApi.notify(user.getId(), "excelExportError", context);
    }
}

From source file:com.daphne.es.showcase.excel.service.ExcelDataService.java

License:Apache License

/**
 * excel 2003/*  ww  w .j  a v  a  2s .com*/
 * ????
 * ?sheet65536(usermodel? ?flush ????)
 * @param user
 * @param contextRootPath
 * @param searchable
 */
@Async
public void exportExcel2003WithUsermodel(final User user, final String contextRootPath,
        final Searchable searchable) {
    int perSheetRows = 60000; //?sheet 6w?
    int totalRows = 0;
    Long maxId = 0L;

    String fileName = generateFilename(user, contextRootPath, "xls");
    File file = new File(fileName);
    BufferedOutputStream out = null;
    try {
        long beginTime = System.currentTimeMillis();

        HSSFWorkbook wb = new HSSFWorkbook();
        while (true) {
            Sheet sheet = wb.createSheet();
            Row headerRow = sheet.createRow(0);
            Cell idHeaderCell = headerRow.createCell(0);
            idHeaderCell.setCellValue("?");
            Cell contentHeaderCell = headerRow.createCell(1);
            contentHeaderCell.setCellValue("");

            totalRows = 1;
            Page<ExcelData> page = null;
            do {
                searchable.setPage(0, pageSize);
                //
                if (!searchable.containsSearchKey("id_in")) {
                    searchable.addSearchFilter("id", SearchOperator.gt, maxId);
                }
                page = findAll(searchable);

                for (ExcelData data : page.getContent()) {
                    Row row = sheet.createRow(totalRows);
                    Cell idCell = row.createCell(0);
                    idCell.setCellValue(data.getId());
                    Cell contentCell = row.createCell(1);
                    contentCell.setCellValue(data.getContent());
                    maxId = Math.max(maxId, data.getId());
                    totalRows++;
                }
                //clear entity manager
                RepositoryHelper.clear();
            } while (page.hasNext() && totalRows <= perSheetRows);

            if (!page.hasNext()) {
                break;
            }
        }

        out = new BufferedOutputStream(new FileOutputStream(file));
        wb.write(out);

        IOUtils.closeQuietly(out);

        if (needCompress(file)) {
            fileName = compressAndDeleteOriginal(fileName);
        }

        long endTime = System.currentTimeMillis();

        Map<String, Object> context = Maps.newHashMap();
        context.put("seconds", (endTime - beginTime) / 1000);
        context.put("url", fileName.replace(contextRootPath, ""));
        notificationApi.notify(user.getId(), "excelExportSuccess", context);
    } catch (Exception e) {
        IOUtils.closeQuietly(out);
        log.error("excel export error", e);
        Map<String, Object> context = Maps.newHashMap();
        context.put("error", e.getMessage());
        notificationApi.notify(user.getId(), "excelExportError", context);
    }
}