利用poi导出excel的代码片段

try {
            OutputStream os = response.getOutputStream();
            response.reset();// 清空输出流
            response.setHeader("Content-disposition",
                "attachment; filename=" + new String("images".getBytes("GB2312"), "iso8859_1")
                        + ".xls");// 设定输出文件头
            response.setContentType("application/msexcel");// 定义输出类型
            /************** 创建一个xls文档 *************/
            HSSFWorkbook workbook = new HSSFWorkbook(); // 定义工作薄
            HSSFCellStyle style = workbook.createCellStyle(); // 获取单元格样式
            /************** 设置单元格样式 *************/
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平
            style.setWrapText(true);
            HSSFSheet sheet = workbook.createSheet(); // 创建sheet
            // 设置表头
            // 创建第一行
            HSSFRow row1 = sheet.createRow(0);
            // 创建列
            HSSFCell cell1 = row1.createCell(0);// 第一列
            HSSFCell cell2 = row1.createCell(1);
            HSSFCell cell3 = row1.createCell(2);
            HSSFCell cell4 = row1.createCell(3);
            // 定义单元格为字符串类型
            cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell3.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell4.setCellType(HSSFCell.CELL_TYPE_STRING);

            cell1.setCellValue("类型/大小");
            cell2.setCellValue("作者 (全部)");
            cell3.setCellValue("地址");
            cell4.setCellValue("时间");
            // 设置列宽
            sheet.setColumnWidth(0, 8000);
            sheet.setColumnWidth(1, 10000);
            sheet.setColumnWidth(2, 5000);
            sheet.setColumnWidth(3, 6000);

            HSSFRow row = null;
            // 添加数据
            for (int r = 1; r <= filelist.size(); r++) // 表示行
            {
                img = filelist.get(r - 1);
                row = sheet.createRow(r);
                row.createCell(0).setCellValue(
                    img.getUploadFileInfo().subStr(img.getUploadFileInfo().getThumbnailurl()) + " "
                            + img.getUploadFileInfo().getSize());
                row.createCell(1).setCellValue(img.getAuthor());
                row.createCell(2).setCellValue(img.getUploadFileInfo().getImgrefurl());
                row.createCell(3).setCellValue(img.getFormatDate());
            }
            workbook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            logger.error("", e);
        }

 

你可能感兴趣的:(poi,Excel)