java excel导出

本文介绍了如何使用Java的Apache POI和EasyPoi库,结合Maven依赖,实现根据预定义模型导出Excel,并演示了数据列表导出、自定义Excel字段注解和创建复杂格式的工作簿。重点讲解了如何处理数据映射和创建Excel响应头。
摘要由CSDN通过智能技术生成

java excel导出

maven

<!--读取excel-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-web -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.1.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-base -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.1.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-annotation -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.1.3</version>
        </dependency>

1.根据已有模型导出

excel格式为
在这里插入图片描述

final String pathDir = System.getProperty("user.dir") + "/crmXls/";
        File savefile = new File(pathDir);
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        TemplateExportParams params = new TemplateExportParams(ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/excel/invoice.xls");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data1",UUID.randomUUID().toString().replace("-", ""));
        map.put("data2",username);
        map.put("data3",shopUserBean.getTel());
        map.put("data4",addressBean.getAddress());
        map.put("data5",orderInfoBean.getCreateTime());
        map.put("data6",orderInfoBean.getOrderNo());
        map.put("data7",goodsBean.getGoodsId());
        map.put("data8",goodsBean.getGoodsName());
        map.put("data9",orderDetailBean.getQty());
        map.put("data10",goodsBean.getPrice());
        map.put("data11",orderInfoBean.getTotalPrice());

        try {

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
            if (workbook == null) {
                log.error("workbook为空");
            }
            String name = pathDir +  "land.xls";
            FileOutputStream fos = new FileOutputStream(name);
            workbook.write(fos);
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

2.获取数据列表导出

public ResultObject exportData(HttpSession session, HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam int id) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        //excel文件添加【姓名】表头
        List<ExcelExportEntity> headers = new ArrayList<>();
        ExcelExportEntity excelentity1 = new ExcelExportEntity("水域数据详细信息", "tag" );
        List<ExcelExportEntity> temp1 = new ArrayList<ExcelExportEntity>();
        temp1.add(new ExcelExportEntity("水域名称", "title"));
        temp1.add(new ExcelExportEntity("边界X", "coordinateX"));
        temp1.add(new ExcelExportEntity("边界Y", "coordinateY" ));
        temp1.add(new ExcelExportEntity("数量", "numbers" ));
        temp1.add(new ExcelExportEntity("用途", "purpose" ));
        temp1.add(new ExcelExportEntity("权属状况", "ownership" ));
        temp1.add(new ExcelExportEntity("生产特性", "prodCharacter" ));
        temp1.add(new ExcelExportEntity("水域简介", "synopsis" ));
        excelentity1.setList(temp1);
        headers.add(excelentity1);

        FishWaterManageBean fishWaterManageBean = dao.fetch(FishWaterManageBean.class,Cnd.where("del","=",0)
        .and("id","=",id));
        if (fishWaterManageBean!=null){
            HashMap<String, Object> map = new HashMap<>();
            Map<String, Object> map1 = new HashMap<>();
            map.put("title",fishWaterManageBean.getTitle());
            map.put("coordinateX",fishWaterManageBean.getCoordinateX());
            map.put("coordinateY",fishWaterManageBean.getCoordinateY());
            map.put("numbers",fishWaterManageBean.getNumbers());
            map.put("purpose",fishWaterManageBean.getPurpose());
            map.put("ownership",fishWaterManageBean.getOwnership());
            map.put("prodCharacter",fishWaterManageBean.getProdCharacter());
            map.put("synopsis",fishWaterManageBean.getSynopsis());
            List<Map<String, Object>> list1 = new ArrayList<>();
            list1.add(map);
            map1.put("tag",list1);
            list.add(map1);
        }

        try {
            FileExportUtil.writeXls(session, response, request, "水域数据.xls");
            ExportParams params = new ExportParams();
            params.setType(ExcelType.XSSF);
            Workbook workbook = ExcelExportUtil.exportExcel(params, headers, list);
            workbook.write(response.getOutputStream());

           //或者写进本地
             //File file = new File("demo.xls");
            //FileOutputStream fout = new FileOutputStream(file);
            //excel.write(fout);
            //fout.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObject.apiError(e.toString());
        }
    }



//--Excel响应
    public static void writeXls(HttpSession session, HttpServletResponse response, HttpServletRequest request, String fileName) throws Exception {
        //--设置响应类型
        response.setContentType(session.getServletContext().getMimeType("xls"));
        response.setContentType("application/vnd.ms-excel");
        //--设置响应头信息(附件形式	PS:以标题为蓝本,拼接扩展名
        String agent = request.getHeader("User-Agent");
        if (agent.contains("MSIE")) {
            // IE浏览器
            response.setHeader("Content-Disposition", "attachment; fileName=" + URLEncoder.encode(fileName, "utf-8"));
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            BASE64Encoder base64Encoder = new BASE64Encoder();
            response.setHeader("Content-Disposition", "attachment; fileName=" + "=?utf-8?B?" + base64Encoder.encode(fileName.getBytes("utf-8")) + "?=");
        } else {
            // 其它浏览器
            response.setHeader("Content-Disposition", "attachment; fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        }
    }

3.直接在表里定义@Excel

List<AgriIrrigatedDto> finalDto = exportMsgList2(ids);//这是获取数据列表
        System.err.println(finalDto);
        try {
            FileExportUtil.writeXls(session, response, request, "农业灌溉灌渠.xls");
            ExportParams exportParams = new ExportParams("农业灌溉灌渠", "农业灌溉灌渠");
            Workbook excel = ExcelExportUtil.exportExcel(exportParams, AgriIrrigatedDto.class, finalDto);

            File file = new File("demo.xls");
            FileOutputStream fout = new FileOutputStream(file);
            excel.write(fout);
            fout.close();

                    } catch (Exception e) {
            log.info(e.getMessage());
            return ResultObject.apiError(""+e);

        }


//AgriIrrigatedDto.class

@Data
public class AgriIrrigatedDto {
    @Excel(name = "灌区名称",  needMerge = true)
    private String data1;

    @Excel(name = "有效灌溉面积(亩)",  needMerge = true)
    private String data2;
    @Excel(name = "实际灌溉面积(亩)",  needMerge = true)
    private String data3;
    @Excel(name = "工程地点(所在乡、镇)",  needMerge = true)
    private String data4;

    @Excel(name = "建设时间(年)",  needMerge = true)
    private String data5;

    @Excel(name = "水源名称",  needMerge = true)
    private String data6;

    @Excel(name = "引水流量(㎡/s)",  needMerge = true)
    private String data7;

4.自己定义格式


HSSFWorkbook workbook = new HSSFWorkbook();
        AnalysisModelListBean listBean = dao.fetch(AnalysisModelListBean.class,Cnd.where("id","=",id));
//        AnalysisModelListBean listBean = new AnalysisModelListBean();

//        listBean.setFirstQuality("{\\\"organization\\\":{\\\"title\\\":\\\"组织结构和人员\\\",\\\"datas\\\":[{\\\"id\\\":1,\\\"data1\\\":\\\"有创建无公害三品一标生产基地申请报告\\\",\\\"number\\\":1,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":2,\\\"data1\\\":\\\"有上级主管部门的批准创建无公害三品一标生产基地的文件\\\",\\\"number\\\":2,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":3,\\\"data1\\\":\\\"有专门机构负责无公害三品一标生产\\\",\\\"number\\\":3,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":4,\\\"data1\\\":\\\"有专人负责无公害三品一标生产\\\",\\\"number\\\":4,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":5,\\\"data1\\\":\\\"有监测机构并正常开展工作\\\",\\\"number\\\":5,\\\"data2\\\":\\\"y\\\"}]},\\\"production\\\":{\\\"title\\\":\\\"生产环境\\\",\\\"datas\\\":[{\\\"id\\\":1,\\\"data1\\\":\\\"有生产园区或有生产区域位置图\\\",\\\"number\\\":1,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":2,\\\"data1\\\":\\\"有生产园区生产面积分布图,园区面积部小于500亩\\\",\\\"number\\\":2,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":3,\\\"data1\\\":\\\"大气质量符合GB3095规定的要求,有最近一次检验报告\\\",\\\"number\\\":3,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":4,\\\"data1\\\":\\\"灌溉水质量符合GB5084规定的要求,有最近一次检验报告\\\",\\\"number\\\":4,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":5,\\\"data1\\\":\\\"土壤质量符合GB15618规定的要求,有最近一次检验报告\\\",\\\"number\\\":5,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":6,\\\"data1\\\":\\\"有基地周围是否有污染源的调查报告\\\",\\\"number\\\":6,\\\"data2\\\":\\\"y\\\"}]},\\\"means\\\":{\\\"title\\\":\\\"生产资料\\\",\\\"datas\\\":[{\\\"id\\\":1,\\\"data1\\\":\\\"有主要生产资料一览表(设施、大型农机具、水源、肥料库、农药库等)\\\",\\\"number\\\":1,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":2,\\\"data1\\\":\\\"基地农药使用的品种和使用量,库存农药品种\\\",\\\"number\\\":2,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":3,\\\"data1\\\":\\\"购买农药记录(包括购买的地点、厂家、种类、时间和数量)\\\",\\\"number\\\":3,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":4,\\\"data1\\\":\\\"化肥储备量,购买化肥记录(包括购买的地点、厂家、种类、时间和数量)\\\",\\\"number\\\":4,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":5,\\\"data1\\\":\\\"有机肥储备量\\\",\\\"number\\\":5,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":6,\\\"data1\\\":\\\"有机肥的检测报告(包括有毒有害物质含量、有害病原菌含量)\\\",\\\"number\\\":6,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":7,\\\"data1\\\":\\\"购买种子记录(包括购买的地点、生产单位、种类、时间和数量)\\\",\\\"number\\\":7,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":8,\\\"data1\\\":\\\"栽培设施的结构、面积\\\",\\\"number\\\":8,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":9,\\\"data1\\\":\\\"棚膜、地膜使用量,废旧地膜的处理\\\",\\\"number\\\":9,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":10,\\\"data1\\\":\\\"有农药残留检测仪器\\\",\\\"number\\\":10,\\\"data2\\\":\\\"y\\\"}]},\\\"process\\\":{\\\"title\\\":\\\"生产过程记录\\\",\\\"datas\\\":[{\\\"id\\\":1,\\\"data1\\\":\\\"栽培种类\\\",\\\"number\\\":1,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":2,\\\"data1\\\":\\\"栽培茬口\\\",\\\"number\\\":2,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":3,\\\"data1\\\":\\\"是否轮作\\\",\\\"number\\\":3,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":4,\\\"data1\\\":\\\"是否休耕\\\",\\\"number\\\":4,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":5,\\\"data1\\\":\\\"栽培方式(露地、设施)\\\",\\\"number\\\":5,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":6,\\\"data1\\\":\\\"栽培畦式、栽培密度\\\",\\\"number\\\":6,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":7,\\\"data1\\\":\\\"灌溉方式(大水漫灌、滴灌、微喷)\\\",\\\"number\\\":7,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":8,\\\"data1\\\":\\\"土地耕层深度\\\",\\\"number\\\":8,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":9,\\\"data1\\\":\\\"无土栽培方式(水培、基质培、有机生态型)\\\",\\\"number\\\":9,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":10,\\\"data1\\\":\\\"栽培品种\\\",\\\"number\\\":10,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":11,\\\"data1\\\":\\\"种子处理\\\",\\\"number\\\":11,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":12,\\\"data1\\\":\\\"育苗方式\\\",\\\"number\\\":12,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":13,\\\"data1\\\":\\\"施基肥种类、数量时间\\\",\\\"number\\\":13,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":14,\\\"data1\\\":\\\"追肥种类、数量、时间及次数\\\",\\\"number\\\":14,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":15,\\\"data1\\\":\\\"设施栽培种CO2施肥情况\\\",\\\"number\\\":15,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":16,\\\"data1\\\":\\\"病虫害发生情况\\\",\\\"number\\\":16,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":17,\\\"data1\\\":\\\"生产中病虫害防治方法、农药施用品种、施用量、施用时间、施用浓度、施用次数和安全间隔期内农药施用情况记录\\\",\\\"number\\\":17,\\\"data2\\\":\\\"y\\\"}]},\\\"records\\\":{\\\"title\\\":\\\"产品记录\\\",\\\"datas\\\":[{\\\"id\\\":1,\\\"data1\\\":\\\"采收时间及产量\\\",\\\"number\\\":1,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":2,\\\"data1\\\":\\\"产品经检测合格证明,有最近一次检验报告\\\",\\\"number\\\":2,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":3,\\\"data1\\\":\\\"产品储存条件\\\",\\\"number\\\":3,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":4,\\\"data1\\\":\\\"产品包装、规格\\\",\\\"number\\\":4,\\\"data2\\\":\\\"y\\\"},{\\\"id\\\":5,\\\"data1\\\":\\\"产品销往地点和时间\\\",\\\"number\\\":5,\\\"data2\\\":\\\"y\\\"}]}}");
        String result = listBean.getFirstQuality();
        result= StringEscapeUtils.unescapeJava(result);
        JSONObject json = JSON.parseObject(result);
        String re1 ="";String re2 ="";String re3 ="";
        String re4 ="";String re5 ="";

        re1 = json.getJSONObject("organization").getString("datas");
        re2 = json.getJSONObject("production").getString("datas");
        re3 = json.getJSONObject("means").getString("datas");
        re4 = json.getJSONObject("process").getString("datas");
        re5 = json.getJSONObject("records").getString("datas");

//
        System.err.println(re1);
        System.err.println(re2);
        System.err.println(re3);
        System.err.println(re4);
        System.err.println(re5);


        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        HSSFSheet sheet = workbook.createSheet("sheet");
        sheet.setColumnWidth(0, 10000);
        sheet.setColumnWidth(1, 8000);
        sheet.setColumnWidth(2, 8000);
        sheet.setColumnWidth(3, 8000);
        sheet.setColumnWidth(4, 10000);
        HSSFRow row0 = sheet.createRow(0);

        HSSFCell cell_000 = row0.createCell(0);
        cell_000.setCellStyle(style);
        cell_000.setCellValue("基地适应性评价");

        CellRangeAddress region1 = new CellRangeAddress(0, 0, 0, 4);
        sheet.addMergedRegion(region1);

        HSSFRow row1 = sheet.createRow(1);
        HSSFRow row2 = sheet.createRow(2);
        HSSFCell cell_00 = row1.createCell(0);
        cell_00.setCellStyle(style);
        cell_00.setCellValue("评价报告名称");
        HSSFCell cell_01 = row1.createCell(1);
        cell_01.setCellStyle(style);
        cell_01.setCellValue("适宜性(%)\n");
        HSSFCell cell_02 = row1.createCell(2);
        cell_02.setCellStyle(style);
        cell_02.setCellValue("评价人员");

        HSSFCell cell_03 = row1.createCell(3);
        cell_03.setCellStyle(style);
        cell_03.setCellValue("评分");

        HSSFCell cell_04 = row1.createCell(4);
        cell_04.setCellStyle(style);
        cell_04.setCellValue("评价结论");

        HSSFCell cell_10 = row2.createCell(0);
        cell_10.setCellStyle(style);
        cell_10.setCellValue(listBean.getData1());
        HSSFCell cell_11 = row2.createCell(1);
        cell_11.setCellStyle(style);
        cell_11.setCellValue(listBean.getData2());

        HSSFCell cell_12 = row2.createCell(2);
        cell_12.setCellStyle(style);
        cell_12.setCellValue(listBean.getData3());

        HSSFCell cell_13 = row2.createCell(3);
        cell_13.setCellStyle(style);
        cell_13.setCellValue(listBean.getData4());

        HSSFCell cell_14 = row2.createCell(4);
        cell_14.setCellStyle(style);
        cell_14.setCellValue(listBean.getData5());

        HSSFRow row3 = sheet.createRow(3);
        HSSFCell cell_30 = row3.createCell(0);
//        cell_20.setCellStyle(style);
        cell_30.setCellValue("组织结构和人员");
        re1= StringEscapeUtils.unescapeJava(re1);
        JSONArray jsonArrayre1 = JSONArray.parseArray(re1);
        for (int i = 0; i < jsonArrayre1.size(); i++){
            String data1 = jsonArrayre1.getJSONObject(i).getString("data1");
            String data2 = jsonArrayre1.getJSONObject(i).getString("data2");
            String ids = jsonArrayre1.getJSONObject(i).getString("id");
            String result1 = "达标";
            if (!"y".equals(data2)){
                result1="不达标";
            }
            HSSFRow row5 = sheet.createRow(4+i);
            HSSFCell cell_50 = row5.createCell(0);
            cell_50.setCellStyle(style);
            cell_50.setCellValue(ids);

            HSSFCell cell_52 = row5.createCell(1);
            cell_52.setCellStyle(style);
            cell_52.setCellValue(data1);

            HSSFCell cell_51 = row5.createCell(5);
            cell_51.setCellStyle(style);
            cell_51.setCellValue(result1);
            CellRangeAddress region2 = new CellRangeAddress(4+i, 4+i, 1, 4);
            sheet.addMergedRegion(region2);
        }

        File file = new File("demo.xls");
        FileOutputStream fout = new FileOutputStream(file);
        workbook.write(fout);
        fout.close();

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值