工作记录:导出内容到excel

用前须知:

XSSFWorkbookHSSFWorkbookSXSSFWorkbook的区别?

HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,扩展名是.xls

XSSFWorkbook:是操作Excel2007的版本,扩展名是.xlsx

对于不同版本的EXCEL文档要使用不同的工具类,如果使用错了,会提示如下错误信息。

org.apache.poi.openxml4j.exceptions.InvalidOperationException

org.apache.poi.poifs.filesystem.OfficeXmlFileException

SXSSFWorkbookpoi3.8版本以后加入的,为了解决写数据时的大数据问题,不过是只能用来写数据,不能读数据,而且格式必须是excel2007

-------------------------------------------分割线----------------------------------------------------

这是action中的部分代码,首先要有个pager分页对象。里面包含的是我们要导出的数据

//查询结果
List<Map> resultList = pager.getResultList();
//标题
String[] headers = { "标题", "责任部门", "到期时间", "超期天数" };
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet("超期问题");
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 30);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一个字体
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
//产生表格标题行
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
   HSSFCell cell = row.createCell(i);
   cell.setCellStyle(style);
   HSSFRichTextString text = new HSSFRichTextString(headers[i]);
   cell.setCellValue(text);
}
//循环,为每个单元格设置值。
for(int i=0;i<resultList.size();i++){
	Map p = resultList.get(i);
	if(p != null){
		row = sheet.createRow(i+1);
		HSSFCell cell0 = row.createCell(0);
		cell0.setCellValue(p.get("CONTENT").toString());
		HSSFCell cell1 = row.createCell(1);
		cell1.setCellValue(p.get("DEP_NAME").toString());
		HSSFCell cell2 = row.createCell(2);
		cell2.setCellValue(p.get("EXPIRATION_TIME").toString());
		HSSFCell cell3 = row.createCell(3);
		cell3.setCellValue(p.get("CQTS").toString());
	}
}
//写文件
HttpServletResponse response = ServletActionContext.getResponse();
OutputStream out = response.getOutputStream();
response.setContentType("application/octet-stream;charset=ISO8859-1");
String filename="超期数据";//文件名称
response.setHeader("Content-Disposition","attachment; filename="+new String(filename.getBytes("GBK"),"ISO8859-1")+".xls");
workbook.write(out); 
try   { 
	 out.close();
 }   catch   (IOException   e)   { 
	 e.printStackTrace(); 
 }

-------------------------------------------华丽的分割线---------------------------------------------

使用SXSSFWorkbook 进行excel的导出:

private void exportExcel(String reportName, List<KqRecord> records) {
        // 定义第一行要显示的数据
        String[] header = new String[9];
        header[0] = "序号";
        header[1] = "考勤机编号";
        header[2] = "部门名称";
        header[3] = "考勤号码";
        header[4] = "姓名";
        header[5] = "考勤时间";
        header[6] = "考勤状态";
        header[7] = "验证方式";
        header[8] = "设备别名";
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setCharacterEncoding("utf-8");
        ServletOutputStream out = null;
        Workbook wb = new SXSSFWorkbook(100);//内存中村100条数据
        // 创建一个sheet
        Sheet sheet = wb.createSheet();
        // 第一行:标题行
        Row rowFirst = null;
        rowFirst = sheet.createRow(0);
        //设置第一行的样式
        Font font = wb.createFont();
        CellStyle cs = wb.createCellStyle();
        font.setColor(IndexedColors.BLACK.index);
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        font.setFontHeightInPoints((short) 12);
        cs.setFillForegroundColor(IndexedColors.TURQUOISE.index);// GOLD
        cs.setFillPattern(CellStyle.SOLID_FOREGROUND);
        rowFirst.setHeightInPoints(20);// 设置行高30
        cs.setAlignment(CellStyle.ALIGN_CENTER);// 水平对齐方式
        cs.setFont(font);
        // 创建第一行,并写入数据与样式
        for (int i = 0; i < header.length; i++) {
            Cell cell = rowFirst.createCell(i);
            cell.setCellStyle(cs);
            cell.setCellValue(header[i]);
        }
        // 创建其他数据行
        Row row = null;
        Cell cell = null;
        KqRecord kqRecord = null;
        for (int i = 0; i < records.size(); i++) {
            row = sheet.createRow(i + 1);
            kqRecord = (KqRecord) records.get(i);
            for (int j = 0; j < header.length; j++) {// 根据有多少个标题,一次每个cell填入数据
                cell = row.createCell(j);
                if (j == 0) {
                    cell.setCellValue(j + 1 + "");
                } else if (j == 1) {
                    cell.setCellValue(kqRecord.getSnId());
                } else if (j == 2) {
                    cell.setCellValue(kqRecord.getDeptName());
                } else if (j == 3) {
                    cell.setCellValue(kqRecord.getEmpNumber());
                } else if (j == 4) {
                    cell.setCellValue(kqRecord.getName());
                } else if (j == 5) {
                    cell.setCellValue(kqRecord.getCheckTime());
                } else if (j == 6) {
                    cell.setCellValue(kqRecord.getCheckType());
                } else if (j == 7) {
                    cell.setCellValue(kqRecord.getValidateflag());
                } else if (j == 8) {
                    cell.setCellValue(kqRecord.getDeviceNmae());
                }
            }
        }
        try {
            response.setHeader("Content-disposition",
                    "attachment; filename=" + java.net.URLEncoder.encode(reportName, "UTF-8") + ".xlsx");
            out = response.getOutputStream();
            // 往外写数据,可以根据需求是写到文件还是写到流
            wb.write(out);
            out.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

 

测试方法:

@Test
    public void test() {
        String[] header = new String[9];
        header[0] = "序号";
        header[1] = "考勤机编号";
        header[2] = "部门名称";
        header[3] = "考勤号码";
        header[4] = "姓名";
        header[5] = "考勤时间";
        header[6] = "考勤状态";
        header[7] = "验证方式";
        header[8] = "设备别名";
        KqRecord k = new KqRecord();
        k.setId("1");
        k.setKqid("1");
        k.setDeptName("11");
        k.setDeviceNmae("dev1");
        k.setName("name");
        k.setCheckTime("2015-01-20 09:19:18.0");
        k.setCheckType("上班打卡");
        k.setValidateflag("1");
        k.setSnId("11");
        List<KqRecord> kqRecords = new ArrayList<KqRecord>();
        kqRecords.add(k);
        exportExcel("导出名称", kqRecords);
    }

你可能感兴趣的:(Excel,导出,2003,2007)