Excel导出实例
在软件开发中,我们经常会遇到将数据输出的事情,输出Excel更是经常用的。在此仅写简单导出Excel的一些代码,其余的根据个人情况适当改写。
导入poi的jar包是必须的。
GZIPOutputStream OutputStream = null;// 创建一个新的ExcelHSSFWorkbook workbook = new HSSFWorkbook();// 创建工作簿HSSFSheet sheet = workbook.createSheet("test");// 创建设置样式的对象HSSFCellStyle cellStyle = workbook.createCellStyle();// 创建调色板HSSFPalette palette = workbook.getCustomPalette();// 设置前景色palette.setColorAtIndex((short)9, (byte)(182), (byte)(182), (byte)(182));// 设置字体样式cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND );// 设置背景色cellStyle.setFillForegroundColor((short)9);// 设置对齐方式cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 创建第一行HSSFRow row = sheet.createRow(0);// 创建第一行第一列HSSFCell cell = row.createCell(0);// 第一行第一列设置样式cell.setCellStyle(cellStyle);// 设置列宽sheet.setColumnWidth(0, 3000);// 设置值cell.setCellValue(new HSSFRichTextString("NAME"));cell = row.createCell(1);cell.setCellStyle(cellStyle);sheet.setColumnWidth(1, 5000);cell.setCellValue(new HSSFRichTextString("AGE"));HSSFCellStyle cellStyle2 = workbook.createCellStyle();cellStyle2.setAlignment(HSSFCellStyle.ALIGN_RIGHT);// 从数据库查出数据循环导入到Excel中,查出数据返回集合list// list封装domain,从domain里取数据for(int i = 0;i < list.size();i++){row = sheet.createRow(i+1);cell = row.createCell(0);TestDomain domain = (TestDomain )list.get(i);cell.setCellValue(new HSSFRichTextString(domain.getName());cell = row.createCell(1);cell.setCellStyle(cellStyle2);cell.setCellValue(new HSSFRichTextString(domain.getAge());}response.reset();response.setContentType("application/vnd.ms-excel");response.setHeader("Content-Encoding", "gzip");response.addHeader("Content-Disposition", "inline;filename=test.xls");outputStream = new GZIPOutputStream(response.getOutputStream());workbook.write(outputStream);outputStream.flush();