poi 5.2 导出

如果能给你带来帮助,不胜荣幸,如果有错误也请批评指正。

  1:maven 依赖,现在好多都是用的poi 3.6 和 poi3.9 的jar,项目升级了,现在得用5.x的了,所以就用5.x的给大家简单的演示,尽可能找依赖相同的,因为不同版本里面的方法什么的会有变化

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.0</version>
</dependency>

  2:后台(网上后台太多了,全是写后台bug的,我就不多说了,我就用最怂的一种给大家展示,仅做展示)

    ①网上随便扒一个工具类,大家可以看一下里面的注释,个别地方说了一下废话

import org.apache.poi.hssf.usermodel.*;

/**
 * excel导出工具
 *
 * @author Tomas·Red
 * @since
 */

public class ExcelExportUtil {

    /**
     * 导出Excel
     * @param sheetName sheet名称
     * @param title 标题
     * @param values 内容
     * @param wb HSSFWorkbook对象
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, String [][]values, HSSFWorkbook wb){
        // 第一步,创建一个HSSFWorkbook,对应一个Excel文件 
     //
你创建 HSSFWorkbook 就是代表创建 .xls(2003)最大导出行数为:65536;创建XSSFWorkbook 代表创建.xlsx(2007)最大行数为:1048576 至于用什么自己定义
        if(wb == null){
            wb = new HSSFWorkbook();
        }
        // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);
        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);
        // 第四步,创建单元格,并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        //style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 样式我给隐藏了,因为5.2的poi,不支持这样写了,我没去查,后期查了之后再修改吧
        //声明列对象
        HSSFCell cell = null;
        //创建标题
        for(int i=0;i<title.length;i++){
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }
        //创建内容
        for(int i=0;i<values.length;i++){
            row = sheet.createRow(i + 1);
            for(int j=0;j<values[i].length;j++){
                //将内容按顺序赋给对应的列对象
                row.createCell(j).setCellValue(values[i][j]);
            }
        }
        return wb;
    }
}

   ②业务层或者控制层代码

@RequestMapping("/handExprot")
    public Object handExprot(HttpServletResponse response, WellEquipmentParam wellEquipmentParam){
        // 导出的数据
        List<Well> list = (List<Well>) mainBusiness.findAll();
        //excel标头
        String[] title = {"title1", "title2", "title3", "title4", "title5", "title6", "title7", "title8"};

        //excel文件名
        String fileName = "活动报名信息表" + System.currentTimeMillis() + ".xls";
        //sheet名
        String sheetName = "活动报名信息表";
        int size = list.size();
        String [][] content = new String[size][8];
     // 循环给单元格赋值
for (int i = 0; i < list.size(); i++) { content[i] = new String[title.length]; Well well = list.get(i); content[i][0] = well.getId() + ""; content[i][1] = well.getWellName() + ""; content[i][2] = well.getWellCode() + ""; content[i][3] = well.getWellType() + ""; content[i][4] = well.getLatitude() + ""; content[i][5] = well.getLongitude() + ""; content[i][6] = well.getWellDepth() + ""; content[i][7] = well.getWellAddress() + ""; } //创建HSSFWorkbook HSSFWorkbook wb = ExcelExportUtil.getHSSFWorkbook(sheetName, title, content, null); //响应到客户端 try { this.setResponseHeader(response, fileName); OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } return null; }
//发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

  到这里后台的方法已经全部写完了。剩下的就是前台了,网上搜的很多都是没有前台的,没有前台你写个der啊,老衲就是前台不会,后来自己东拼西凑了一个前台,大家凑合着看吧

 

export function handExprot(data) {
    let consturl=process.env.SERVER_API + "/WellController/handExprot" + "?" + qs.stringify(data, { indices: false });
    var xhr = new XMLHttpRequest();
    console.log({consturl})
    xhr.open("get", consturl, true); // get、post都可
    xhr.responseType = "blob";  // 转换流
    xhr.setRequestHeader("token",window.localStorage.getItem("token")); //加请求头
    xhr.onload = function() {
        // debugger
        if (this.status == 200) {
            var blob = this.response;
            var a = document.createElement("a")
            var url = window.URL.createObjectURL(blob)
            a.href = url
            a.download = "导出文件.xls"  //
        }
        a.click()
        window.URL.revokeObjectURL(url)
    }
    xhr.send();
}

到这里就完了,后台有很多大家可以取随便抄,但是前台不能单纯的ajax去请求。要注意属性

  

posted @ 2022-08-03 11:31  也许已没有也许  阅读(552)  评论(0编辑  收藏  举报