Java POI 导出 Excel 到本地详细实例(附jar包,测试代码,测试结果图)

poi导出Excel测试实例,附jar包,测试Java代码,详细注释,测试结果图。


下面是poi的jar包的某度云盘
链接:http://pan.baidu.com/s/1kVBEZNh 密码:74v7


以下是详细测试代码,附带详细注释。

package com.lxk.poiTest;

import com.google.common.collect.Lists;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;

import java.io.*;
import java.util.List;

/**
 * poi jar 包测试
 * <p>
 * Created by lxk on 2016/11/15
 */
public class PoiTest {
    public static void main(String[] args) {
        List<Integer> all = getListData();
        poiTest(all);
    }

    /**
     * 导出Excel测试
     *
     * @param all 导出数据集合
     */
    private static void poiTest(List<Integer> all) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表对象并命名
        HSSFSheet sheet = workbook.createSheet("sheet1");
        sheet.setDefaultColumnWidth(20);
        // 创建列表名称样式
        HSSFCellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setWrapText(true);// 设置长文本自动换行
        headerStyle.setAlignment(CellStyle.ALIGN_CENTER);//居中
        HSSFFont font = workbook.createFont();
        font.setBold(true);// 字体加粗
        headerStyle.setFont(font);

        // 创建表头,列
        HSSFRow headerRow = sheet.createRow(0);
        headerRow.setHeightInPoints(25f);

        HSSFCell header1 = headerRow.createCell(0);//0列
        header1.setCellValue("第一列名称");
        header1.setCellStyle(headerStyle);
        HSSFCell header2 = headerRow.createCell(1);//1列
        header2.setCellValue("第二列名称");
        header2.setCellStyle(headerStyle);

        //一般数据样式
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        for (int i = 0; i < all.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            row.setHeightInPoints(20f);

            HSSFCell cell = row.createCell(0);//参数为:列数index = 0,此处是第一列
            cell.setCellValue(all.get(i));
            cell.setCellStyle(cellStyle);

            HSSFCell cell1 = row.createCell(1);//参数为:列数index = 1,此处是第二列
            cell1.setCellValue(all.get(i));
            cell1.setCellStyle(cellStyle);
        }

        //总述:将HSSFWorkbook中的文件流数,据输出即写到文件d:text.xls
        //声明变量,一般在哪用,就在哪声明,这行代码要是放在方法第一行也不是不可以,但是习惯不好,
        //像这样的小问题,是没人会给你说的,除了我这哎叨叨的大师兄以外。
        OutputStream outputStream = null;
        try {
            File file = new File("d:text.xls");//可能会抛异常:NullPointerException
            outputStream = new FileOutputStream(file);//1.打开资源:输出文件流;2.可能会抛异常:FileNotFoundException
            /* 关于 HSSFWorkbook.write(OutputStream stream) throws IOException {}
             | 方法的原文注释如下:
             |   Method write - write out this workbook to an Outputstream.  Constructs
             |   a new POI POIFSFileSystem, passes in the workbook binary representation  and
             |   writes it out.
             |   @param stream - the java OutputStream you wish to write the XLS to
             |   @exception IOException if anything can't be written.
             */
            //write会自动新建一个xls模板,然后把数据以二进制的形式写到里面,然后再写到输出流中
            workbook.write(outputStream);//可能会抛异常:IOException
        } catch (IOException e) {
            System.out.println(e.getMessage());//异常要处理给人看,要么log,要么...
        } finally {
            //正确关闭文件流的姿势
            try {
                workbook.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * 获得导出数据集合
     */
    private static List<Integer> getListData() {
        List<Integer> all = Lists.newArrayList();
        for (int i = 0; i < 10; i++) {
            all.add(i);
        }
        return all;
    }
}

测试结果图:



会自动在d:盘目录下生成个文件,然后写入内容。








通常业务需求都是客户端一个导出按钮,发送请求到服务端,服务端写一个接口导出报表到客户端,客户可以自行下载。无论Struts或者springMVC均可。 @RequestMapping("Export") @ResponseBody public String getAll(HttpServletRequest request,HttpServletResponse response) throws IOException{ //集合为需要导出数据,数据查询得到,这里测试就不写了。 List<User> list=new ArrayList<User>(); // 生成Excel文件 HSSFWorkbook hssfWorkbook = new HSSFWorkbook(); HSSFSheet sheet = hssfWorkbook.createSheet("测试数据"); // 表头 HSSFRow headRow = sheet.createRow(0); headRow.createCell(0).setCellValue("姓名"); headRow.createCell(1).setCellValue("手机号码"); headRow.createCell(2).setCellValue("年龄"); // 表格数据 for (User user : list) { HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1); dataRow.createCell(0).setCellValue(user.getName()); dataRow.createCell(1).setCellValue(user.getPhone()); dataRow.createCell(2).setCellValue(user.getAge()); } // 下载导出(一个流两个头) // 设置头信息 response.setContentType( "application/vnd.ms-excel"); // MIME .jpg .xls .mp3 .avi .txt .exe String filename = "驾驶员数据.xls"; //如果为Struts框架,获得request和response可用ServletActionContext String agent = request .getHeader("user-agent"); filename = FileUtils.encodeDownloadFilename(filename, agent); response.setHeader("Content-Disposition", "attachment;filename=" + filename); ServletOutputStream outputStream = response .getOutputStream(); //输出 hssfWorkbook.write(outputStream); // 关闭 hssfWorkbook.close(); //System.out.println("导出成功"); return "success"; }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值