Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“可怜的模糊实现”。支持的excel格式如下:

  1. HSSF - 提供读写Microsoft Excel XLS格式档案的功能。
  2. XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能。
  3. HWPF - 提供读写Microsoft Word DOC格式档案的功能。
  4. HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
  5. HDGF - 提供读Microsoft Visio格式档案的功能。
  6. HPBF - 提供读Microsoft Publisher格式档案的功能。
  7. HSMF - 提供读Microsoft Outlook格式档案的功能。

其官方的api文档地址为:poi api地址

先来一个简单的入门例子。先用poi声明一个excel工作薄,然后生成excel表格的表头,在表头里面生产单元格,往单元格填写数据。类似于html中table的创建方式。然后再利用io流,将刚才生成的工作薄写入本地文件。

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
//下面是和数据导出有关的包
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ExportExcel {

    public void Export(){
        // 声明一个工作薄
        HSSFWorkbook wb = new HSSFWorkbook();
        //声明一个单子并命名
        HSSFSheet sheet = wb.createSheet("学生表");
        //给单子名称一个长度
        sheet.setDefaultColumnWidth(10);
        // 生成一个样式
        HSSFCellStyle style = wb.createCellStyle();
        //创建第一行(也可以称为表头)
        HSSFRow row = sheet.createRow(0);
        //样式字体居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //给表头第一行一次创建单元格
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("学生编号");
        cell.setCellStyle(style);
        cell = row.createCell(1);
                cell.setCellValue("学生姓名");
                cell.setCellStyle(style);
                cell = row.createCell(2);
                cell.setCellValue("学生性别");
                cell.setCellStyle(style); 

               //添加一些数据,这里先写死,大家可以换成自己的集合数据
               List<Student> list = new ArrayList<Student>();
               list.add( new Student(111, "张三", "男") );
               list.add( new Student(112, "李四", "男") );
               list.add( new Student(113, "王五", "女") );
               list.add( new Student(114, "张大帅", "男") );

               //向单元格里填充数据
               for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(list.get(i).getId());
                row.createCell(1).setCellValue(list.get(i).getName());
                row.createCell(2).setCellValue(list.get(i).getSex());
            }

        try {
            //默认导出到E盘下
            FileOutputStream out = new FileOutputStream("E://学生表.xls");
            wb.write(out);
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这时候,E盘生成一个叫做"学生表.xsl"的excel文件,四行三列的表格。其中list是为了更好的封装数据,一般List的数据应该从service层中拿到(假设你是一个web项目),Person的java bean定义如下:

public class Student {
    private Integer id;
    private String name;
    private String sex;

    public Student() {
    }

    public Student(Integer id, String name, String sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
}

好了,现在可以结合web项目来做一个到处表格的页面,前端的页面可以省略掉。后台controller如下:

    /**
     * desp:导出excel表格
     * @param model
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportExcel")
    public String exportExcel(HttpServletRequest req, HttpServletResponse resp) {
        //声明一个工作薄
        HSSFWorkbook wb = new HSSFWorkbook();
        //申明一个单子并命名
        HSSFSheet sheet = wb.createSheet("个人收入表");
        //给单元格一个默认的长度(原文字符个数)
        sheet.setDefaultColumnWidth(10);
        //生成样式
        HSSFCellStyle style = wb.createCellStyle();
        //样式字体居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        //创建表头,也就是表头
        HSSFRow header = sheet.createRow(0);
        //给表头创建单元格
        HSSFCell cell = header.createCell(0);
        cell.setCellValue("姓名");
        cell.setCellStyle(style);
        cell = header.createCell(1);
        cell.setCellValue("股票收入(万)");
        cell.setCellStyle(style);
        cell = header.createCell(2);
        cell.setCellValue("基金收入(万)");
        cell.setCellStyle(style);
        cell = header.createCell(3);
        cell.setCellValue("工资收入(万)");
        cell.setCellStyle(style);
        cell = header.createCell(4);
        cell.setCellValue("总收入(万)");
        cell.setCellStyle(style);

        //获取数据 TODO 应该从调用serivce得到数据,serivce再调用dao得到数据
        List<Person> list = new ArrayList<Person>();
        list.add(new Person(1, "林冲", 100, 50, 20));
        list.add(new Person(2, "宋江", 80, 40, 10));
        list.add(new Person(3, "卢俊义", 80, 40, 10));

        //向单元格里填充数据
        for(final Person person : list) {
            HSSFRow row = sheet.createRow(person.getId());
            row.createCell(0).setCellValue(person.getName());
            row.createCell(1).setCellValue(person.getStockIncome());
            row.createCell(2).setCellValue(person.getFoundationIncome());
            row.createCell(3).setCellValue(person.getSalaryIncome());
            row.createCell(4).setCellValue(
                    person.getFoundationIncome() + person.getStockIncome() + person.getSalaryIncome()
                    );
        }

        //写文件,将生成的表单写入服务器本地文件
        FileOutputStream os = null;
        try {
            os = new FileOutputStream("E://个人收入表.xls");
            wb.write(os);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try{
                if(os != null) {
                    os.close();
                    os = null;
                }
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
        ReportExcel.download(filePath, resp);
        return null;
    }
    /**
     * 将服务器生成的excel表下载到客户端
     * @param path
     * @param response
     */
    public static void download(String path, HttpServletResponse response) {
        // path是指欲下载的文件的路径。
        File file = null;
        OutputStream toClient = null;
        InputStream fis = null;

        try {
            file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 以流的形式下载文件。
            fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);

            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(filename.getBytes(),"iso-8859-1")+".xlsx");
            toClient.write(buffer);
            toClient.flush();       

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if(file != null) {
                file.delete();
            }
            try {
                if(fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if(toClient != null) {
                    toClient.close();
                    toClient = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

在这个controller中的exportExcel方法,先在服务器磁盘用poi生成一个.xsl文件,然后调用工具类“ReportExcel.download(filePath, resp);”,将服务器本地的刚才生成的文件输出到客户端。同时这里要注意,由于这里下载中用到了response的输出流,而返回视图的jsp页面也会用到response的输出流,它会报错流已经被打开,那么这里可以把controller中的返回视图设置为void,既不返回任何试图。

apache poi导出excel报表的更多相关文章

  1. 使用Apache POI导出Excel小结--导出XLS格式文档

    使用Apache POI导出Excel小结 关于使用Apache POI导出Excel我大概会分三篇文章去写 使用Apache POI导出Excel小结--导出XLS格式文档 使用Apache POI ...

  2. poi导出Excel报表多表头双层表头、合并单元格

    效果图: controller层方法: /**     *      * 导出Excel报表     * @param request     * @return     *      */    @ ...

  3. apache POI 导出excel相关方法

    apache POI 操作excel无比强大.同时有操作word和ppt的接口. 下面讲解poi中常用方法. 1,设置列宽 HSSFSheet sheet = wb.getSheetAt(0); sh ...

  4. 使用org.apache.poi导出Excel表格

    public HSSFWorkbook MakeExcel(List<TransactionLogVO> logList) { // SimpleDateFormat sdf = new ...

  5. Apache POI导出excel表格

    项目中我们经常用到导出功能,将数据导出以便于审查和统计等.本文主要使用Apache POI实现导出数据. POI中文文档 简介 ApachePOI是Apache软件基金会的开放源码函式库,POI提供A ...

  6. Apache POI导出excel

    public String exportXls(HttpServletRequest request, HttpServletResponse response) { try { HSSFWorkbo ...

  7. java 通过Apache poi导出excel代码demo实例

    package com.zuidaima.excel.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutput ...

  8. Java使用POI实现数据导出excel报表

    Java使用POI实现数据导出excel报表 在上篇文章中,我们简单介绍了java读取word,excel和pdf文档内容 ,但在实际开发中,我们用到最多的是把数据库中数据导出excel报表形式.不仅 ...

  9. poi导出excel

    Java使用poi组件导出excel报表,能导出excel报表的还可以使用jxl组件,但jxl想对于poi功能有限,jxl应该不能载excel插入浮动层图片,poi能很好的实现输出excel各种功能, ...

随机推荐

  1. 【javascript激增的思考04】MVC与Backbone.js(beta)

    前言 最近整理了很多前端面试题的东西,今天又去参加了一次面试,不知各位烦不烦,我反正有点累了,于是我们今天继续回到我们前段时间研究的问题,我们再来看看MVC吧. 什么是MVC 又回到这个问题了,到底什 ...

  2. 【高级功能】使用Web存储

    Web存储允许我们在浏览器里保存简单的键/值数据.Web存储和cookie很相似,但它有着更好的实现方式,能保存的数据量也很大.这两种类型共享相同的机制,但是被保存数据的可见性和寿命存在区别. PS: ...

  3. 总结CSS3新特性(媒体查询篇)

    CSS3的媒体查询是对CSS2媒体类型的扩展,完善; CSS2的媒体类型仅仅定义了一些设备的关键字,CSS3的媒体查询进一步扩展了如width,height,color等具有取值范围的属性; medi ...

  4. CSS常用样式(三)

    一.2D变换 1.transform   设置或检索对象的转换 取值: none::以一个含六值的(a,b,c,d,e,f)变换矩阵的形式指定一个2D变换,相当于直接应用一个[a,b,c,d,e,f] ...

  5. 后台运行进程(background job)

    在一些日常业务中,总有一些长时间处理的任务,系统运行这些任务需要一晚甚至一个周末. 这就需要后台运行单元(background work process)来完成,而且其是不会发生超时(time out ...

  6. 兼容Android的水波纹效果

    Android的水波纹效果只有高版本才有,我们希望自己的应用在低版本用低版本的阴影,高版本用水波纹,这怎么做呢?其实,只要分drawable和drawablev21两个文件夹就好了. 普通情况下的se ...

  7. Android开发实战(二十一):浅谈android:clipChildren属性

    实现功能: 1.APP主界面底部模块栏 2.ViewPager一屏多个界面显示 3......... 首先需要了解一下这个属性的意思 ,即 是否允许子View超出父View的返回,有两个值true . ...

  8. HTTPS学习总结

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 21.0px Verdana; color: #393939 } span.s1 { } HTTPS学习总结 ...

  9. iOS 开发之路(登陆验证调用WebService)二

    swift3.0下使用Alamofire调用Webservice遇到的一些问题以及解决方案. 首先是针对没有证书的https下的接口处理问题(ps:不推荐在正式版本中使用),manager.reque ...

  10. sublime text 3 常用快捷键 、常用插件

    常用快捷键 查找( Ctrl + P ) 找到任何东西 - :+行号   定位到具体的行 - @+符号  js的函数名, css的选择器名 - #+关键字  定位到特定的关键字 命令面板 (Ctrl ...