如何使用POI导出excel表格,以及处理浏览器无法识别下载文件的问题

废话不多说, 直接上代码.

1. 依赖

<properties>
    <poi.version>3.11</poi.version>
</properties>


<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>${poi.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>${poi.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>${poi.version}</version>
</dependency>

2. 代码

3.1 控制层

@RequestMapping(value = "/exportStoreOrderList")
public String exportXls(){
    ///创建excel代码
    exportService.exportXls();
    return NONE;
}

接口省略

3.2 serviceImpl

@Override
public void exportXls() {
    try {
        //查询分区所有数据
        List<Order> listOrder = orderDao.findAll();

        //当前excel创建对象
        HSSFWorkbook hwb = new HSSFWorkbook();
        HSSFSheet createSheet = hwb.createSheet();//创建sheet页

         /*设置列宽*/
        createSheet.setColumnWidth(0, 10000);
        /*设置字体,边框,这个有心思的可以去详细找找教程,这里实在不好弄*/
        HSSFCellStyle style = hwb.createCellStyle();
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 靠左
        // 字体
        HSSFFont font = hwb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 12);// 14号字体



        HSSFRow titleRow = createSheet.createRow(0);//创建标题行
        titleRow.createCell(0).setCellValue("订单编号");
        titleRow.createCell(1).setCellValue("商品编号");
        titleRow.createCell(2).setCellValue("商品名");
        titleRow.createCell(3).setCellValue("商品价格");
        titleRow.createCell(4).setCellValue("下单时间");

        if(listOrder != null){
            for (Order data: listOrder ) {
                ///循环在标题行后添加数据
                int lastRowNum = createSheet.getLastRowNum()+1;//当前需要增加行的下标 
                HSSFRow dataRow = createSheet.createRow(lastRowNum);
                dataRow.createCell(0).setCellValue(data.getId());
                dataRow.createCell(1).setCellValue(data.getGoodId());
                dataRow.createCell(2).setCellValue(data.getGoodNum());
                dataRow.createCell(3).setCellValue(data.getPrice());
                dataRow.createCell(4).setCellValue(data.getTime());
            }
        }

        //边框
        for (int j = 0; j <= 4 ; j++) {
             dataRow.getCell(j).setCellStyle(style);
        }

        //一个流 两个头

        //文件名称
        String filename = "数据.xls";

        //获取User-agent 当前是哪个浏览器
        String userAgent = ServletActionContext.getRequest().getHeader("User-Agent");
        // 这里使用到FileUtils工具类进行编码
        String encodeFilename = FileUtils.encodeDownloadFilename(filename, userAgent);
        ServletActionContext.getResponse().setHeader("content-disposition", "filename="+encodeFilename);
        //文件后缀
        ServletActionContext.getResponse().setContentType("application/vnd.ms-excel;charset=UTF-8");
        //输出流对象
        ServletOutputStream outputStream = ServletActionContext.getResponse().getOutputStream();
        hwb.write(outputStream);
        hwb.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

不对文件名进行编码处理的话, 有些浏览器无法识别下载文件

3.3 FileUtils

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;

public class FileUtils {
        /**
         * 下载文件时,针对不同浏览器,进行附件名的编码
         * 
         * @param filename
         *            下载文件名
         * @param agent
         *            客户端浏览器
         * @return 编码后的下载附件名
         * @throws IOException
         */
        public static String encodeDownloadFilename(String filename, String agent)
                throws IOException {
            // 如果是火狐浏览器
            if (agent.contains("Firefox")) { 
                 filename = "=?UTF-8?B?"
                    + Base64.getEncoder().encodeToString(filename.getBytes("utf-8"))
                    + "?=";
                filename = filename.replaceAll("\r\n", "");
            // IE及其他浏览器
            } else { 
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+"," ");
            }
            return filename;
        }
}

猜你喜欢

转载自blog.csdn.net/zzzgd_666/article/details/80583043