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

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

Introduction

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

Prototype

private void write(POIFSFileSystem fs) throws IOException 

Source Link

Document

Writes the workbook out to a brand new, empty POIFS

Usage

From source file:com.krawler.esp.servlets.exportExcel.java

License:Open Source License

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

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

    // Create a row and put some cells in it. Rows are 0 based.
    HSSFRow row = sheet.createRow(0);//from w ww . j a va  2  s .  c om
    HSSFCell cell = row.createCell(0);
    cell.setCellValue(1);

    // Or do it on one line.
    row.createCell(1).setCellValue(1.2);

    row.createCell(3).setCellValue(true);
    // Write the output
    OutputStream out = response.getOutputStream();
    wb.write(out);
    out.close();
}

From source file:com.leosys.core.utils.ExcelUtil.java

public void exportExcel(List<?> dataList, OutputStream out) throws Exception {
    HSSFWorkbook workbook = null;
    HSSFSheet sheet = null;/*from w w  w. j av a 2  s.c o  m*/
    HSSFRow row = null;
    HSSFCell cell = null;
    HSSFCellStyle titleStyle = null;
    int rowIndex = 0;
    try {
        workbook = new HSSFWorkbook();// 
        sheet = workbook.createSheet("?");// ?      
        sheet.setDefaultColumnWidth((short) 30);// 15   
        titleStyle = workbook.createCellStyle();//?
        titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        titleStyle.setFillForegroundColor(HSSFColor.WHITE.index);
        titleStyle.setFillBackgroundColor(HSSFColor.WHITE.index);
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFFont font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setFontHeightInPoints((short) 17);
        titleStyle.setFont(font);

        row = sheet.createRow(rowIndex++);
        row.setHeight((short) 600);
        for (short i = 0; i < headArr.length; i++) {
            cell = row.createCell(i); //?
            if (i == 0)
                cell.setCellValue(new HSSFRichTextString(title));
            cell.setCellStyle(titleStyle);
        }
        // ???    
        sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) (headArr.length - 1)));

        titleStyle = workbook.createCellStyle();
        titleStyle.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
        titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        font.setFontHeightInPoints((short) 13);
        titleStyle.setFont(font);// ??   
        row = sheet.createRow(rowIndex++);// 
        for (short i = 0; i < headArr.length; i++) {
            cell = row.createCell(i);
            cell.setCellStyle(titleStyle);
            cell.setCellValue(new HSSFRichTextString(headArr[i]));
        }
        //?
        titleStyle = workbook.createCellStyle();
        titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        if (dataList == null || dataList.isEmpty())
            return;
        short dataType = 0;//
        if (dataList.get(0) instanceof Map<?, ?>)
            dataType = 1;
        else if (dataList.get(0) instanceof List<?>)
            dataType = 2;
        if (dataType == 0) {
            String[] dataArr = null;
            for (Object data : dataList) {
                dataArr = (String[]) data;
                if (dataArr == null)
                    continue;
                row = sheet.createRow(rowIndex++);
                for (short i = 0; i < headArr.length; i++) {
                    if (i < dataArr.length) {
                        Object val = dataArr[i];
                        if (rendererArr != null && rendererArr[i] != null)
                            val = rendererArr[i].renderer(dataArr[i], i, dataArr);
                        fillCell(row, titleStyle, font, i, val);
                    }
                }
            }
        } else if (dataType == 1) {
            Map<?, ?> map = null;
            for (Object data : dataList) {
                map = (Map<?, ?>) data;
                if (map == null)
                    continue;
                Object[] dataArr = map.values().toArray();
                if (dataArr == null)
                    continue;
                row = sheet.createRow(rowIndex++);
                for (short i = 0; i < headArr.length; i++) {
                    if (i < dataArr.length) {
                        Object val = dataArr[i];
                        if (rendererArr != null && rendererArr[i] != null)
                            val = rendererArr[i].renderer(dataArr[i], i, dataArr);
                        fillCell(row, titleStyle, font, i, val);
                    }
                }
            }
        } else if (dataType == 2) {
            List<?> list = null;
            for (Object data : dataList) {
                list = (List<?>) data;
                if (list == null || list.isEmpty())
                    continue;
                row = sheet.createRow(rowIndex++);
                for (short i = 0; i < headArr.length; i++) {
                    if (i < list.size()) {
                        Object val = list.get(i);
                        if (rendererArr != null && rendererArr[i] != null)
                            val = rendererArr[i].renderer(list.get(i), i, list);
                        fillCell(row, titleStyle, font, i, val);
                    }
                }
            }
        } else
            throw new Exception("excel???");
        workbook.write(out);
    } catch (Exception e) {
        throw new Exception("excel" + e.getMessage());
    } finally {
        //         if(out != null){
        //            try {
        //               out.close();
        //            } catch (IOException e) {}
        //         }
    }
}

From source file:com.liferay.portlet.documentlibrary.action.EditEntryAction.java

License:Open Source License

public static void exportDocumentData(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws NumberFormatException, PortalException, SystemException {

    long file_id = 0;

    String fileEntryIds = ParamUtil.getString(resourceRequest, "fileEntryIds");
    String[] fileentires = fileEntryIds.split(",");
    List<Long> tempResults = new ArrayList<Long>();

    if (!fileEntryIds.isEmpty()) {
        if (fileentires[0].equals("true")) {

            for (int i = 1; i < fileentires.length; i++) {
                DLFileEntry FileEntry = DLFileEntryLocalServiceUtil
                        .getDLFileEntry(Long.parseLong(fileentires[i]));
                file_id = FileEntry.getFileEntryId();
                tempResults.add(file_id);

            }/*  w w  w.  jav a  2s.  c o  m*/
        } else {
            for (int i = 0; i < fileentires.length; i++) {
                DLFileEntry FileEntry = DLFileEntryLocalServiceUtil
                        .getDLFileEntry(Long.parseLong(fileentires[i]));
                file_id = FileEntry.getFileEntryId();
                tempResults.add(file_id);

            }
        }
    }

    try {

        HSSFWorkbook hwb = new HSSFWorkbook();
        HSSFSheet sheet = hwb.createSheet("Site Information");
        org.apache.poi.ss.usermodel.Font font = hwb.createFont();
        font.setFontHeightInPoints((short) 11);
        font.setFontName("Arial");
        font.setItalic(false);
        font.setStrikeout(false);
        font.setBoldweight(org.apache.poi.ss.usermodel.Font.BOLDWEIGHT_BOLD);
        CellStyle style = hwb.createCellStyle();

        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setBorderRight(CellStyle.BORDER_THIN);

        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        style.setFont(font);

        CellStyle filterStyle = hwb.createCellStyle();

        org.apache.poi.ss.usermodel.Font filterfont = hwb.createFont();
        filterfont.setFontHeightInPoints((short) 9);
        filterfont.setFontName("Courier New");
        filterfont.setItalic(false);
        filterfont.setStrikeout(false);
        filterfont.setBoldweight(org.apache.poi.ss.usermodel.Font.BOLDWEIGHT_BOLD);
        filterStyle.setFont(filterfont);

        filterStyle.setBorderBottom(CellStyle.BORDER_THIN);
        filterStyle.setBorderLeft(CellStyle.BORDER_THIN);
        filterStyle.setBorderTop(CellStyle.BORDER_THIN);
        filterStyle.setBorderRight(CellStyle.BORDER_THIN);
        HSSFRow rowhead = sheet.createRow((short) 2);
        rowhead.createCell((short) 0).setCellValue("S.No.");
        rowhead.createCell((short) 1).setCellValue("Title ");
        rowhead.createCell((short) 2).setCellValue("Site Name ");
        rowhead.createCell((short) 3).setCellValue("Category Type");
        rowhead.createCell((short) 4).setCellValue("Com");
        rowhead.createCell((short) 5).setCellValue("Upload Date");
        rowhead.createCell((short) 6).setCellValue("File Type");

        int index = 3;
        int sno = 0;

        for (int i = 0; i < tempResults.size(); i++)

        {

            sno++;

            DLFileEntry objdlfileentry = DLFileEntryLocalServiceUtil.getDLFileEntry(tempResults.get(i));
            docs_customData objdocs_customData = null;
            try {
                objdocs_customData = docs_customDataLocalServiceUtil.getfileEntry(tempResults.get(i));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }

            String com = "";
            if (objdocs_customData != null) {
                com = objdocs_customData.getCom();
            }

            String siteName = "";
            if (objdocs_customData != null) {
                siteName = objdocs_customData.getSite();
            }

            String doccategory = "";
            if (objdocs_customData != null) {
                doccategory = objdocs_customData.getCategory();
            }

            HSSFRow row = sheet.createRow((short) index);
            row.createCell((short) 0).setCellValue(sno);
            row.createCell((short) 1).setCellValue(objdlfileentry.getTitle());
            row.createCell((short) 2).setCellValue(siteName);
            row.createCell((short) 3).setCellValue(doccategory);
            row.createCell((short) 4).setCellValue(com);
            row.createCell((short) 5).setCellValue(objdlfileentry.getModifiedDate());
            row.createCell((short) 6).setCellValue(objdlfileentry.getMimeType());

            index++;

        }

        resourceResponse.setContentType("application/vnd.ms-excel");
        resourceResponse.addProperty("Content-Disposition", "attachment;filename=Document_Listing.xls");
        OutputStream fileOut = resourceResponse.getPortletOutputStream();
        hwb.write(fileOut);
        fileOut.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:com.lition.service.impl.OwnedServiceImpl.java

/**
 * POI??/*from  www  .  j av a 2  s  .  c o m*/
 */
@Override
public InputStream getOutExcelDate() {
    //1.?
    String headTitle[] = { "id", "?", "??", "", "??" };

    //2.Dao??
    List<OwnedVehicle> list = dao.queryAll();

    //3.?HSSFWorkbook
    HSSFWorkbook wb = new HSSFWorkbook();

    //4.?sheet
    HSSFSheet sheet = wb.createSheet("?");

    //5.?
    HSSFCellStyle style = wb.createCellStyle();
    // ??
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    style.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);

    //6.
    HSSFRow row0 = sheet.createRow(0);
    //7.??
    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));

    HSSFCell row0cell0 = row0.createCell(0);
    row0cell0.setCellValue("?");
    row0cell0.setCellStyle(style);

    HSSFRow row1 = sheet.createRow(1);

    for (int i = 0; i < headTitle.length; i++) {
        HSSFCell row0cell = row1.createCell(i);
        row0cell.setCellValue(headTitle[i]);
        row0cell.setCellStyle(style);
    }

    for (int i = 0; i < list.size(); i++) {
        HSSFRow row = sheet.createRow(i + 2);

        //ID
        HSSFCell cell0 = row.createCell(0);
        cell0.setCellValue(list.get(i).getId());
        cell0.setCellStyle(style);

        //?
        HSSFCell cell1 = row.createCell(1);
        cell1.setCellValue(list.get(i).getVehicleId());
        cell1.setCellStyle(style);

        //??
        HSSFCell cell2 = row.createCell(2);
        cell2.setCellValue(list.get(i).getDepid());
        cell2.setCellStyle(style);

        //
        HSSFCell cell3 = row.createCell(3);
        cell3.setCellValue(list.get(i).getModel());
        cell3.setCellStyle(style);

        //??
        HSSFCell cell4 = row.createCell(4);
        cell4.setCellValue(list.get(i).getVehicleUsageId());
        cell4.setCellStyle(style);
    }

    //?inputstream;
    try {
        OutputStream out = new FileOutputStream("abc.xls");
        wb.write(out);
        out.close();
        InputStream in = new FileInputStream("abc.xls");
        return in;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:com.luna.showcase.excel.service.ExcelDataService.java

License:Apache License

/**
 * workbook//from   w w w . j  a va 2 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.hasNextPage() && totalRows <= perSheetRows);

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

            IOUtils.closeQuietly(out);

            if (!page.hasNextPage()) {
                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.luna.showcase.excel.service.ExcelDataService.java

License:Apache License

/**
 * excel 2003/* w w  w  . j  av  a 2  s . c  om*/
 * ????
 * ?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.hasNextPage() && totalRows <= perSheetRows);

            if (!page.hasNextPage()) {
                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);
    }
}

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

License:Apache License

/**
 * @param excel_name/*from  w w w .j av  a 2s.c o m*/
 *            ?Excel+??
 * @param headList
 *            ExcelHead?
 * @param fieldList
 *            ExcelField?
 * @param dataList
 *            Excel?
 * @throws Exception
 */
public static void createExcel(String excel_name, String[] headList, String[] fieldList,
        List<Map<String, Object>> dataList) throws Exception {
    // Excel 
    HSSFWorkbook workbook = new HSSFWorkbook();

    // Excel???
    // ???""?
    // HSSFSheet sheet = workbook.createSheet("");
    HSSFSheet sheet = workbook.createSheet();
    // 0?
    HSSFRow row = sheet.createRow(0);
    // ===============================================================
    for (int i = 0; i < headList.length; i++) {

        // 0??
        HSSFCell cell = row.createCell(i);
        // ?
        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        // ?
        cell.setCellValue(headList[i]);
    }
    // ===============================================================

    for (int n = 0; n < dataList.size(); n++) {
        // 1?
        HSSFRow row_value = sheet.createRow(n + 1);
        Map<String, Object> dataMap = dataList.get(n);
        // ===============================================================
        for (int i = 0; i < fieldList.length; i++) {

            // 0??
            HSSFCell cell = row_value.createCell(i);
            // ?
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            // ?
            cell.setCellValue(objToString(dataMap.get(fieldList[i])));
        }
        // ===============================================================
    }

    // ?
    FileOutputStream fOut = new FileOutputStream(excel_name);
    // Excel 
    workbook.write(fOut);
    fOut.flush();
    // ??
    fOut.close();
    //System.out.println("[" + excel_name + "]" + "?...");
}

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

License:Apache License

/**
 * @param excel_name//  w w w.j  a va 2  s. co m
 *            ?Excel+??
 * @param headList
 *            ExcelHead?
 * @param fieldList
 *            ExcelField?
 * @param dataList
 *            Excel?
 * @throws Exception
 */
public static void createExcel(String excel_name, List<String> headList, List<String> fieldList,
        List<Map<String, Object>> dataList) throws Exception {
    // Excel 
    HSSFWorkbook workbook = new HSSFWorkbook();

    // Excel???
    // ???""?
    // HSSFSheet sheet = workbook.createSheet("");
    HSSFSheet sheet = workbook.createSheet();
    // 0?
    HSSFRow row = sheet.createRow(0);
    // ===============================================================
    for (int i = 0; i < headList.size(); i++) {

        // 0??
        HSSFCell cell = row.createCell(i);
        // ?
        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        // ?
        cell.setCellValue(headList.get(i));
    }
    // ===============================================================

    for (int n = 0; n < dataList.size(); n++) {
        // 1?
        HSSFRow row_value = sheet.createRow(n + 1);
        Map<String, Object> dataMap = dataList.get(n);
        // ===============================================================
        for (int i = 0; i < fieldList.size(); i++) {

            // 0??
            HSSFCell cell = row_value.createCell(i);
            // ?
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            // ?
            cell.setCellValue(objToString(dataMap.get(fieldList.get(i))));
        }
        // ===============================================================
    }

    // ?
    FileOutputStream fOut = new FileOutputStream(excel_name);
    // Excel 
    workbook.write(fOut);
    fOut.flush();
    // ??
    fOut.close();
    //System.out.println("[" + excel_name + "]" + "?...");
}

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

License:Apache License

/**
 * //from w  w w  . j  a v a  2  s .  co  m
 * @param excel_name
 *            ?Excel+??
 * @param headList
 *            ExcelHead
 * @param valueList
 *            Excel?
 * @throws Exception
 */
public static void bulidExcel(String excel_name, String[] headList, List<String[]> valueList) throws Exception {
    // Excel 
    HSSFWorkbook workbook = new HSSFWorkbook();

    // Excel???
    // ???""?
    // HSSFSheet sheet = workbook.createSheet("");
    HSSFSheet sheet = workbook.createSheet();
    // 0?
    HSSFRow row = sheet.createRow(0);
    // ===============================================================
    for (int i = 0; i < headList.length; i++) {

        // 0??
        HSSFCell cell = row.createCell(i);
        // ?
        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        // ?
        cell.setCellValue(headList[i]);
    }
    // ===============================================================

    for (int n = 0; n < valueList.size(); n++) {
        // 1?
        HSSFRow row_value = sheet.createRow(n + 1);
        String[] valueArray = valueList.get(n);
        // ===============================================================
        for (int i = 0; i < valueArray.length; i++) {

            // 0??
            HSSFCell cell = row_value.createCell(i);
            // ?
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            // ?
            cell.setCellValue(valueArray[i]);
        }
        // ===============================================================
    }

    // ?
    FileOutputStream fOut = new FileOutputStream(excel_name);
    // Excel 
    workbook.write(fOut);
    fOut.flush();
    // ??
    fOut.close();
    //System.out.println("[" + excel_name + "]" + "?...");
}

From source file:com.lushapp.modules.sys.web.BugController.java

License:Apache License

/**
 * Excel//from   w w  w .  j a v a  2 s .c o  m
 */
@SuppressWarnings("unchecked")
@RequestMapping(value = { "exportExcel" })
public void exportExcel(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws Exception {
    // ????
    final String fileName = "?.xls";
    OutputStream outStream = null;
    try {
        //
        response.setContentType(WebUtils.EXCEL_TYPE);
        //?
        WebUtils.setDownloadableHeader(request, response, fileName);
        //session??
        List<PropertyFilter> sessionFilters = (List<PropertyFilter>) session.getAttribute(SSSION_SEARCH);
        List<Bug> bugs = null;
        if (sessionFilters != null) {
            bugs = bugManager.find(sessionFilters, "orderNo", Page.ASC);
        } else {
            bugs = bugManager.getAll("id", Page.ASC);
        }
        //bugBug?Dictionary??
        for (Bug bug : bugs) {
            String dicStringName = "";
            if (StringUtils.isNotBlank(bug.getType())) {
                dicStringName = DictionaryUtils.getDictionaryNameByDV(DictionaryUtils.DIC_BUG, bug.getType());
                bug.setTypeName(dicStringName);
            }

        }
        HSSFWorkbook workbook = new ExportExcel<Bug>().exportExcel("?", Bug.class, bugs);
        outStream = response.getOutputStream();
        workbook.write(outStream);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            outStream.flush();
            outStream.close();
        } catch (IOException e) {

        }
    }
}