java 利用apache 的 poi 操作servlet去写 excel表

来源:互联网 发布:mysql 主从配置 编辑:程序博客网 时间:2024/06/06 14:19

因为java的通用性,被抓去搞了几天后台,最近要弄一个excel导出,于是就想到了apache提供的poi工具,于是去http://poi.apache.org/找找,因为自己的是maven项目,所以就加个依赖引入一下包,其它的可以去下载jar放到自己仓库里面然后依赖或者直接放入项目的libs中,

  <dependency>     <groupId>org.apache.poi</groupId>     <artifactId>poi</artifactId>     <version>3.8</version>  </dependency>

接着就是api的调用了,先明确excel是怎么组成的,最外层是一个xls文件,然后打开后是各种sheet,里面再有各种索引定位的cell,

这样就可以很容易了解poi提供的几个类的意思了,

   // 声明一个工作区  HSSFWorkbook workbook = new HSSFWorkbook();  // 生成一个sheet  HSSFSheet sheet = workbook.createSheet("sheet的名字");  // 接着就是用sheet去操纵row和cell去放对应的数据了  // 几个可能用的着的类:=  // 获取到样式style   HSSFCellStyle style = workbook.createCellStyle();  // 获取到字体style  HSSFFont font = workbook.createFont();  style.setFont(font);  // 声明一个画图管理器</span>  HSSFPatriarch patriarch = sheet.createDrawingPatriarch();  //定义excel用的注释的大小以及所处的位置  HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 3, 1, ( short) 5, 3));  comment.setString(new HSSFRichTextString("注释内容"));// 设置注释内容   comment.setAuthor("anchorname");// 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.


在web与在java中将excel输出的区别就是输出流的设置

servlet中对response要做一下设置:

 response.setHeader("Content-Type", "application/vnd.ms-excel;charset=UTF-8");  response.addHeader("Content-Disposition", "attachment;filename=mvdata_"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+".xls");
java中就是指定fileoutputstream中file的位置就ok了


web中具体操作如下:

@SuppressWarnings("unchecked")@RequestMapping("exportData")public @ResponseBody void exportData(HttpServletResponse response, HttpServletRequest request) throws Exception {            Map<String, Object> result = service.getData(startIndex, pageSize);  String[] columnName = {"标题1", "标题2"};//表格中列名         List<List<String>> allRows =  Lists.newArrayList();//每一行的数据  for(Info info:list){//javabean 为Info , 里面含有2个属性为 name, age       List<String> infoList = Lists.newArrayList();       infoList.add(info.getName());       infoList.add(info.getAge());                allRows.add(infoList);  }          response.setHeader("Content-Type", "application/vnd.ms-excel;charset=UTF-8");   response.addHeader("Content-Disposition", "attachment;filename="EXCEL的名字.xls");          OutputStream out = response.getOutputStream();          HSSFWorkbook wb = new HSSFWorkbook();                    out = exportExcel(wb, "sheet1", Arrays.asList(columnNameStrs), allRows, out);//自己封装了方法,因为在util类中,所以就提出来都写在下面,具体方法如下                out.close();}public static OutputStream exportExcel(HSSFWorkbook wb, String sheetName, List<String> columnNames, List<List<String>> allRows, OutputStream out) throws IOException {writeSheet(wb, sheetName, columnNames, allRows);        wb.write(out);        out.flush();        return out;}public static void writeSheet(HSSFWorkbook wb, String sheetName, List<String> columnNames, List<List<String>> allRows) {        HSSFSheet sheet = wb.createSheet(sheetName);        short index = 0;        for (String columnName : columnNames) {            sheet.setColumnWidth(index, 6500);            index++;        }                if(!BlankUtil.isBlank(columnNames))//判断传进来的标题是否为空            writeColumnNames(wb, sheet, columnNames, 0);//在第一行写标题        if(!BlankUtil.isBlank(allRows))//判断传进来的数据是否为空            writeData(wb, sheet, allRows, 1);在第二行写数据}public static void writeColumnNames(HSSFWorkbook wb, HSSFSheet sheet, List<String> columnNames, int rowIndex) {        HSSFRow row = sheet.createRow(rowIndex);//拿到row        HSSFCellStyle headerStyle = wb.createCellStyle();//拿到style,具体style设置参看api,我这里直接用的默认的        short index = 0;        for (String columnName : columnNames) {            HSSFCellUtil.createCell(row, index, columnName, headerStyle);//创建cell,并且写入内容            index++;        }}public static void writeData(HSSFWorkbook wb, HSSFSheet sheet, List<List<String>> allRows, int rowIndex) {//具体调用同上,就是从第2行开始写数据        int rowCount = rowIndex;        HSSFCellStyle normalStyle =wb.createCellStyle();        for (List<String> everyRow : allRows) {            short index = 0;            HSSFRow row = sheet.createRow(rowCount);            row.setHeight((short)300);            for (String cell : everyRow) {                HSSFCellUtil.createCell(row, index, cell, normalStyle);                index++;            }            rowCount++;        }}




好了,这样的话通过浏览器访问 http://ip:port/web.xml中配置的项目根目录/exportData  就能够导出excel出来了,具体这边不是很详细,如果需要详细的话建议大家看下官方的api吧,就这样吧


如有问题,联系方式:iamwsbear@gmail.com



0 0