精华内容
下载资源
问答
  • easyexcel导出到指定文件
    2022-04-19 16:06:13
    @DataLog(operationName = "导出经营业绩指标", methodType = MethodTypeEnum.UPDATE_TYPE)
        @ApiOperation(value = "导出经营业绩指标")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "jxkh2200", value = "考核批次id", required = true),
                @ApiImplicitParam(name = "jxkh0700", value = "考核表id", required = true)
        })
        @ApiOperationSupport(order = 62)
        @GetMapping(value =Urls.PlanMake.XtExportBusinessTargetList)
        public JsonObject<Map<String, Object>> exportExcel(HttpServletResponse response,HttpServletRequest request,String jxkh2200,String jxkh0700) {
            return pmJxkhPlanmakeService.exportExcel(response,request,jxkh2200,jxkh0700);
        }

    serviceimpl:

    public JsonObject<Map<String, Object>> exportExcel(HttpServletResponse response,HttpServletRequest request, String jxkh2200, String jxkh0700, String objectid) {
            //创建HSSFWorkbook对象
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建样式
            HSSFCellStyle style = this.creatHeaderStyle(workbook);
            HSSFCellStyle headerStyle = this.creatHeaderStyle(workbook);
            //建立sheet对象
            HSSFSheet sheet = workbook.createSheet();
            //获取父指标
            List<PmJxkhPlandetail> pmJxkhPlandetails=pmJxkhPlanmakeMapper.getJxkhPlandetailsByB00(jxkh2200,jxkh0700,objectid);
            //获取子指标
            for(PmJxkhPlandetail plandetail: pmJxkhPlandetails){
                List<PmJxkhPlandetail> child=pmJxkhPlanmakeMapper.getJxkhPlandetailsChild(plandetail.getTaskid());
                plandetail.setChildren(child);
            }
            //设置表头
            String[] header = new String[]{"指标类别", "考核指标", "定量指标:指标定义或计算公式/定性指标:评价内容", "指标类型", "评价标准","数据信息来源","指标权重","指标权重小计","评分主体","完成值","完成情况", "得分"};
            int childTotal = 0;
            int headerLength = 0;
            //设置文件数据
            if (pmJxkhPlandetails.size() != 0) {
                List<Integer> childNum = new ArrayList<>();
                for (PmJxkhPlandetail meter : pmJxkhPlandetails) {
                    if (meter.getChildren() != null && !meter.getChildren().isEmpty()) {
                        childNum.add(meter.getChildren().size());
                    }
                }
                for (Integer integer : childNum) {
                    childTotal += integer;
                }
                this.creatHeader(sheet,  header, childNum, pmJxkhPlandetails, childTotal, headerStyle);
            }
            //下载文件
            try {
                //获取当前日期
                SimpleDateFormat formatter= new SimpleDateFormat("yyyyMMdd");
                Date date = new Date(System.currentTimeMillis());
                String time=formatter.format(date);
                //设置文件名
                String fileName = new String(((String)name+"_经营业绩指标"+time).getBytes("gb2312"), "ISO8859-1");
                String safeName = "";
                if (StringUtils.isNotBlank(fileName)) {
                    safeName = StrUtil.removeAny(fileName, StrUtil.CR, StrUtil.LF, StrUtil.CRLF,
                            StrUtil.TAB, StrUtil.HTML_APOS, "\"", ";");
                } else {
                    safeName = UUID.randomUUID().toString().replace("-", "");
                }
                safeName += ".xls";
                //输出Excel
                OutputStream output = response.getOutputStream();
                response.reset();
                //设置响应头
                response.setContentType("application/octet-stream");
                response.setHeader("Content-disposition", "attachment; filename=" + safeName);
                workbook.write(output);
                output.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
            return new JsonSuccessObject<>();
        }

    excel样式设置

    public HSSFCellStyle creatHeaderStyle(HSSFWorkbook workbook) {
            HSSFCellStyle style = workbook.createCellStyle();
            // 生成一个字体并设置字体格式
            HSSFFont font = workbook.createFont();
            font.setFontHeightInPoints((short) 12);
            font.setFontName("宋体");
            // 把字体 应用到当前样式
            style.setFont(font);
            //下边框
            style.setBorderBottom(BorderStyle.THIN);
            //左边框
            style.setBorderLeft(BorderStyle.THIN);
            //上边框
            style.setBorderTop(BorderStyle.THIN);
            //右边框
            style.setBorderRight(BorderStyle.THIN);
            //水平居中
            style.setAlignment(HorizontalAlignment.CENTER);
            //垂直居中
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            //自动换行
            style.setWrapText(true);
            return style;
        }

    设置文件数据方法:

    private void creatHeader(HSSFSheet sheet, String[] header, List<Integer> childNum, List<PmJxkhPlandetail> pmJxkhPlandetails, int childTotal, HSSFCellStyle style) {
            //在sheet里创建前三行,参数为行索引
            HSSFRow row1 = sheet.createRow(0);
            HSSFRow row2 = sheet.createRow(1);
            HSSFRow row3 = sheet.createRow(2);
            //向表头添加数据
            int length = header.length;
            for (int i = 0; i < length; i++) {
                HSSFCell cell = row1.createCell(i);
                HSSFCell cell1 = row2.createCell(i);
                HSSFCell cell2 = row3.createCell(i);
                if (i <= length -1) {
                    cell.setCellValue(header[i]);
                }
                HSSFWorkbook aa= new HSSFWorkbook();
                HSSFFont font = aa.createFont();
                font.setBold(true);
                style.setFont(font);
                cell.setCellStyle(style);
                cell1.setCellStyle(style);
                cell2.setCellStyle(style);
            }
            //表格数据
            for (int i = 0; i < pmJxkhPlandetails.size(); i++) {
                int number = 0;
                int number1 = 0;
                for (int j = 0; j < i; j++) {
                    number = number + childNum.get(j);
                }
                for (int m = 0; m <= i; m++) {
                    number1 = number1 + childNum.get(m);
                }
                for(int a = 0; a < pmJxkhPlandetails.get(i).getChildren().size(); a++){
                    HSSFRow row4 = sheet.createRow(number+3+a);
                    if(0==a){
                        //考核类别
                        HSSFCell cell1 = row4.createCell(0);
                        cell1.setCellValue(pmJxkhPlandetails.get(i).getTaskname());
                        cell1.setCellStyle(style);
                        //指标权重小计
                        HSSFCell cell8 = row4.createCell(7);
                        cell8.setCellValue(String.valueOf(pmJxkhPlandetails.get(i).getTaskweight())+"%");
                        cell8.setCellStyle(style);
                    }
                    HSSFCell cell2 = row4.createCell(1);
                    HSSFCell cell3 = row4.createCell(2);
                    HSSFCell cell4 = row4.createCell(3);
                    HSSFCell cell5 = row4.createCell(4);
                    cell2.setCellValue(pmJxkhPlandetails.get(i).getChildren().get(a).getTaskname());
                    cell3.setCellValue(pmJxkhPlandetails.get(i).getChildren().get(a).getTaskdes());
                    cell4.setCellValue("定量");
                    cell5.setCellValue(pmJxkhPlandetails.get(i).getChildren().get(a).getEvaluation());
                    cell2.setCellStyle(style);
                    cell3.setCellStyle(style);
                    cell4.setCellStyle(style);
                    cell5.setCellStyle(style);
                }
            }
            //合并单元格
            for (int i = 0; i < pmJxkhPlandetails.size(); i++) {
                int number = 0;
                int number1 = 0;
                for (int j = 0; j < i; j++) {
                    number = number + childNum.get(j);
                }
                for (int m = 0; m <= i; m++) {
                    number1 = number1 + childNum.get(m);
                }
                int start = 3;
                //单元格等于一条时不合并
                if(number1-number>1) {
                    CellRangeAddress cra = new CellRangeAddress(start + number, start-1 + number1, 0, 0);
                    //在sheet里增加合并单元格
                    sheet.addMergedRegion(cra);
                    //边框线
                    RegionUtil.setBorderBottom(BorderStyle.THIN, cra, sheet);
                    RegionUtil.setBorderTop(BorderStyle.THIN, cra, sheet);
                    RegionUtil.setBorderLeft(BorderStyle.THIN, cra, sheet);
                    RegionUtil.setBorderRight(BorderStyle.THIN, cra, sheet);
                    CellRangeAddress cra1 = new CellRangeAddress(start + number, start-1 + number1, 7, 7);
                    //在sheet里增加合并单元格
                    sheet.addMergedRegion(cra1);
                    //边框线
                    RegionUtil.setBorderBottom(BorderStyle.THIN, cra1, sheet);
                    RegionUtil.setBorderTop(BorderStyle.THIN, cra1, sheet);
                    RegionUtil.setBorderLeft(BorderStyle.THIN, cra1, sheet);
                    RegionUtil.setBorderRight(BorderStyle.THIN, cra1, sheet);
                }
            }
    //        //设置列宽
            for (int i = 0; i < header.length; i++) {
                // 调整每一列的宽度
                sheet.autoSizeColumn(i);
                sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 13 / 10);
            }
            sheet.setColumnWidth(1,  (int)((35 + 0.72) * 256));
            sheet.setColumnWidth(2,  (int)((35 + 0.72) * 256));
            sheet.setColumnWidth(4,  (int)((35 + 0.72) * 256));
            // 合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
            for (int i = 0; i < length; i++) {
                CellRangeAddress cra = new CellRangeAddress(0, 2, i, i);
                sheet.addMergedRegion(cra);
            }
        }

    更多相关内容
  • EasyExcel导出Excel文件

    2022-07-14 18:06:35
    功能十分强大,能省去我们很多的编码,下面来通过一个例子,看看如何使用EasyExcel导出Excel文件的我们从数据库读取User实体对象数据,然后使用EasyExcel写入HttpServletResponse输出流中,在浏览器就可以下载导出...

    介绍

    EasyExcel是阿里巴巴出品的Excel文件处理工具,功能十分强大,能省去我们很多的编码,下面来通过一个例子,看看如何使用EasyExcel导出Excel文件的

    准备

    我们从数据库读取User实体对象数据,然后使用EasyExcel写入到HttpServletResponse输出流中,在浏览器就可以下载导出的Excel文件了

    POM

    主要有EasyExcel依赖

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.7.1</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.example</groupId>
        <artifactId>excel</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>excel</name>
        <description>excel</description>
        <properties>
            <java.version>1.8</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.2.2</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <!--excel-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>easyexcel</artifactId>
                <version>2.2.3</version>
            </dependency>
    
            <!--json-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.69</version>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <excludes>
                            <exclude>
                                <groupId>org.projectlombok</groupId>
                                <artifactId>lombok</artifactId>
                            </exclude>
                        </excludes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    

    User实体

    @ExcelProperty(value = “id”) 表示导出的Excel文件列名为id,其他同理

    package com.example.excel.entity;
    
    import com.alibaba.excel.annotation.ExcelProperty;
    import com.alibaba.excel.annotation.format.DateTimeFormat;
    import lombok.Data;
    
    import java.math.BigDecimal;
    import java.util.Date;
    
    @Data
    public class User {
    
        @ExcelProperty("id")
        private String id;
    
        @ExcelProperty("username")
        private String username;
    
        @ExcelProperty("password")
        private String password;
    
        @ExcelProperty("address")
        private String address;
    
        @ExcelProperty("email")
        private String email;
    
        @ExcelProperty("profile")
        private String profile;
    
        @ExcelProperty("birthday")
        @DateTimeFormat("yyyy-MM-dd")
        private Date birthday;
    
        @ExcelProperty("registerDay")
        @DateTimeFormat("yyyy-MM-dd")
        private Date registerDay;
    
        @ExcelProperty("loginDay")
        @DateTimeFormat("yyyy-MM-dd")
        private Date loginDay;
    
        @ExcelProperty("status")
        private Integer status;
    
        @ExcelProperty("account")
        private BigDecimal account;
    
        @ExcelProperty("balance")
        private BigDecimal balance;
    
        @ExcelProperty("age")
        private Integer age;
    
        @ExcelProperty("sex")
        private Integer sex;
    
        @ExcelProperty("avatar")
        private String avatar;
    
        @ExcelProperty("level")
        private Integer level;
    
    }
    
    

    ExcelUtil

    实现浏览器导出下载Excel文件,写入本地文件也类似,可参考:EasyExcel使用

    package com.example.excel.util;
    
    import com.alibaba.excel.EasyExcel;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.net.URLEncoder;
    import java.util.List;
    
    /**
     * @description: ExcelUtil
     * @author: zj
     * @date: 2022-07-14 17:07
     */
    public class ExcelUtil {
    
        public static void exportExcel(List<?> objects, Class clazz, String fileName,
                                       String sheetName, HttpServletResponse response) throws IOException {
    
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
    
            // 设置防止中文名乱码
            String exportName = URLEncoder.encode(fileName, "utf-8");
            String sheetSubName = URLEncoder.encode(sheetName, "utf-8");
    
            // 文件下载方式(附件下载还是在当前浏览器打开)
            response.setHeader("Content-disposition", "attachment;filename=" +
                    exportName + ".xlsx");
    
            // 向Excel中写入数据
            EasyExcel.write(response.getOutputStream(), clazz)
                    .sheet(sheetSubName)
                    .doWrite(objects);
    
        }
    
    }
    

    Controller

    实现从MySQL读取数据,写入HttpServletResponse流中的主要逻辑

    package com.example.excel.controller;
    
    import com.example.excel.entity.User;
    import com.example.excel.mapper.UserMapper;
    import com.example.excel.util.ExcelUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.List;
    
    /**
     * @description: Excel
     * @author: zj
     * @date: 2022-07-14 17:02
     */
    @RestController
    @Slf4j
    public class ExcelController {
    
        @Resource
        private UserMapper userMapper;
    
    
        @GetMapping("/excel")
        public void excel(HttpServletResponse response) throws IOException {
    
            long st = System.currentTimeMillis();
    
            List<User> users = userMapper.selectSub(0, 10000);
    
            ExcelUtil.exportExcel(users, User.class, "user_info", "sheet_one", response);
    
            log.info("export excel success, cost {} s.", (System.currentTimeMillis() - st) / 1000);
    
        }
    
    }
    

    效果

    浏览器输入接口地址下载Excel文件

    浏览器输入localhost/excel

    在这里插入图片描述

    在这里插入图片描述

    导出文件

    在这里插入图片描述

    APIFox

    注意:返回的是文件流

    在这里插入图片描述

    展开全文
  • easyexcel 导出excel文件

    2021-11-22 16:08:22
    easyexcel 引入: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.4</version> </dependency&...

    easyexcel 引入:

            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-collections4</artifactId>
                <version>4.4</version>
            </dependency>
    
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>easyexcel</artifactId>
                <version>2.2.3</version>
            </dependency>
    

    MAIN:

    import com.alibaba.excel.EasyExcel;
    import com.alibaba.excel.ExcelWriter;
    import com.alibaba.excel.annotation.ExcelIgnore;
    import com.alibaba.excel.annotation.ExcelProperty;
    import com.alibaba.excel.annotation.format.DateTimeFormat;
    import com.alibaba.excel.annotation.format.NumberFormat;
    import com.alibaba.excel.write.metadata.WriteSheet;
    import com.google.common.collect.Lists;
    import java.math.BigDecimal;
    import java.util.Date;
    import java.util.List;
    import lombok.Data;
    
    /**
     * 类${file_name}的实现描述:TODO 类实现描述
     *
     * @Author: za-qishaohui
     * @Date: 2021/11/22 15:40
     */
    public class WriteTest {
    
      private static List<DemoData> data() {
        List<DemoData> list = Lists.newArrayList();
        for (int i = 0; i < 10; i++) {
          DemoData data = new DemoData();
          data.setString("字符串" + i);
          data.setDate(new Date());
          data.setDoubleData(0.5678);
          data.setNumData(new BigDecimal("56.01234"));
          list.add(data);
        }
        return list;
      }
    
      @Data
      public static class DemoData {
    
        @ExcelProperty("字符串标题")
        private String string;
        @ExcelProperty("日期标题")
        @DateTimeFormat("yyyy-MM-dd")
        private Date date;
        @ExcelProperty("数字标题1")
        @NumberFormat("#.##%")
        private Double doubleData;
    
        @ExcelProperty("数字标题2")
        @NumberFormat("#.##")
        private BigDecimal numData;
        /**
         * 忽略这个字段
         */
        @ExcelIgnore
        private String ignore;
      }
    
      /**
       * 最简单的写
       * <p>1. 创建excel对应的实体对象 参照{@link DemoData}
       * <p>2. 直接写即可
       */
      public static void main(String[] args) {
        // 写法1
        String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        System.out.println(fileName);
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());
    
        // 写法2
        fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        System.out.println(fileName);
        // 这里 需要指定写用哪个class去写
        ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
        excelWriter.write(data(), writeSheet);
        // 千万别忘记finish 会帮忙关闭流
        excelWriter.finish();
      }
    }
    
    

    工具类:

    import java.io.File;
    import java.io.InputStream;
    
    public class TestFileUtil {
    
    
        public static InputStream getResourcesFileInputStream(String fileName) {
            return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
        }
    
        public static String getPath() {
            return TestFileUtil.class.getResource("/").getPath();
        }
    
        public static File createNewFile(String pathName) {
            File file = new File(getPath() + pathName);
            if (file.exists()) {
                file.delete();
            } else {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
            }
            return file;
        }
    
        public static File readFile(String pathName) {
            return new File(getPath() + pathName);
        }
    
        public static File readUserHomeFile(String pathName) {
            return new File(System.getProperty("user.home") + File.separator + pathName);
        }
    }
    
    展开全文
  • 通过easyExcel导出(简洁版)

    千次阅读 2021-10-20 10:12:33
    第一步: 导入依赖 <!-- 导处Excel --> <dependency>...easyexcel</artifactId> <version>3.0.0-beta3</version> </dependency> 第二步: 新建方法类 package c

    第一步:
    导入依赖

        <!-- 导处Excel -->
        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>easyexcel</artifactId>
          <version>3.0.0-beta3</version>
        </dependency>
    

    第二步:
    新建方法类

    package com.lc.yangzi.module.marketing.sell;
    
    import lombok.extern.slf4j.Slf4j;
    import com.alibaba.excel.EasyExcel;
    import com.alibaba.excel.support.ExcelTypeEnum;
    import org.apache.poi.util.IOUtils;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    import java.util.List;
    
    /**
     * Excel工具类
     */
    @Slf4j
    public class ExcelUtils {
    
        /**
         * 导出Excel(07版.xlsx)到指定路径下
         *
         * @param path      路径
         * @param excelName Excel名称
         * @param sheetName sheet页名称
         * @param clazz     Excel要转换的类型
         * @param data      要导出的数据
         */
        public static void export2File(String path, String excelName, String sheetName, Class clazz, List data) {
            String fileName = path.concat(excelName).concat(ExcelTypeEnum.XLSX.getValue());
            EasyExcel.write(fileName, clazz).sheet(sheetName).doWrite(data);
        }
    
        /**
         * 导出Excel(07版.xlsx)到web
         *
         * @param response  响应
         * @param excelName Excel名称
         * @param sheetName sheet页名称
         * @param clazz     Excel要转换的类型
         * @param data      要导出的数据
         * @throws Exception
         */
        public static void export2Web(HttpServletResponse response, String excelName, String sheetName, Class clazz, List data) throws Exception {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            excelName = URLEncoder.encode(excelName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + excelName + ExcelTypeEnum.XLSX.getValue());
            EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(data);
        }
    
        /**
         * 将指定位置指定名称的Excel导出到web
         *
         * @param response  响应
         * @param path      文件路径
         * @param excelName 文件名称
         * @return
         * @throws UnsupportedEncodingException
         */
        public static String export2Web4File(HttpServletResponse response, String path, String excelName) throws UnsupportedEncodingException {
            File file = new File(path.concat(excelName).concat(ExcelTypeEnum.XLSX.getValue()));
            if (!file.exists()) {
                return "文件不存在!";
            }
    
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            excelName = URLEncoder.encode(excelName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + excelName + ExcelTypeEnum.XLSX.getValue());
    
            try (
                    FileInputStream in = new FileInputStream(file);
                    ServletOutputStream out = response.getOutputStream();
            ) {
                IOUtils.copy(in, out);
                return "导出成功!";
            } catch (Exception e) {
                log.error("导出文件异常:", e);
            }
    
            return "导出失败!";
        }
    
    }
    
    

    第二步:
    新建要导出的列表类

    package com.lc.yangzi.module.marketing.sell.customerinfo.domain;
    
    import com.alibaba.excel.annotation.ExcelIgnore;
    import com.alibaba.excel.annotation.ExcelProperty;
    import com.alibaba.excel.annotation.write.style.ColumnWidth;
    import lombok.Data;
    
    @Data
    public class CustomerInfoExcel {
    
        @ColumnWidth(20) // 定义列宽
        @ExcelProperty(value = {"客户名称"}, index = 0)
        private String customerName;//客户名称
        @ColumnWidth(20) // 定义列宽
        @ExcelProperty(value = {"客户等级"}, index = 1)
        private Integer customerLevel;//客户等级:A,B,C,D
        @ColumnWidth(20) // 定义列宽
        @ExcelProperty(value = {"地址"}, index = 2)
        private String address;//地址
        @ColumnWidth(20) // 定义列宽
        @ExcelProperty(value = {"联系电话"}, index = 3)
        private String contactPhone;//联系电话
        @ColumnWidth(20) // 定义列宽
        @ExcelProperty(value = {"审核状态"}, index = 4)
        private String auditStatusName;//状态
        @ColumnWidth(20) // 定义列宽
        @ExcelProperty(value = {"提货状态"}, index = 5)
        private String pickingStatusName;//提货状态
        @ColumnWidth(20) // 定义列宽
        @ExcelProperty(value = {"管理人"}, index = 6)
        private String managerUserName;//管理人姓名(多个逗号分隔)
    
    
        @ExcelIgnore
        private Integer auditStatus;//审核状态审核状态:0草稿1审核中2已完结
        @ExcelIgnore
        private Long id;//主键ID
        @ExcelIgnore
        private Long orgId;//和组织管联 yz_sys_org where category = 3、
        @ExcelIgnore
        private Integer pickingStatus;//提货状态
        @ExcelIgnore
        private Long createUserId;//创建人
    }
    
    

    第四步:
    调用方法

        //导出Excel
        @RequestMapping(value="/exportExcel", method = RequestMethod.GET)
        public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
            try {
                String customerId = request.getParameter("customerId");
                String auditStatus = request.getParameter("auditStatus");
                String pickingStatus = request.getParameter("pickingStatus");
    
                if(StringUtils.isBlank(customerId)){
                    customerId="0";
                }if(StringUtils.isBlank(auditStatus)){
                    auditStatus="-1";
                }if(StringUtils.isBlank(pickingStatus)){
                    pickingStatus="0";
                }
                List<CustomerInfoExcel> list = customerInfoService.selectAllCustomerInfoExcel(Long.parseLong(customerId),Integer.parseInt(auditStatus),Integer.parseInt(pickingStatus));
                ExcelUtils.export2Web(response, "客户信息", "客户信息", CustomerInfoExcel.class, list);
            } catch (Exception e) {
                log.error("报表导出异常:", e);
            }
        }
    
    展开全文
  • 使用easyExcel导出文档快速操作
  • EasyExcel 动态导出指定

    万次阅读 2021-07-21 15:32:15
    EasyExcel使用 EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目。...根据官方文档,有两种导出方式,一种需要手动关闭文件流,一种自动关闭文件流,在此我选择自动关闭文件流的方式。 ExcelWriterBuild
  • 最近需要实现Excel文件导出,于是乎选择了EasyExcel组件来做这件事。 二、代码实现 ·1、依赖导入 <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</...
  • EasyExcel导出中文名文件不显示

    千次阅读 2020-07-31 15:25:27
    * 获取文件名称 * * @param name * @return */ public static String getFileName(String name){ long newTime = System.currentTimeMillis(); String fileName=name + newTime; log.info("文件名fileName=...
  • 使用EasyExcel导出数据模板

    千次阅读 2021-04-09 17:34:16
    ​ 最近在做项目的时候用到了阿里的EasyExcel,用它来将数据导出到一个固定excel模板之中,主要是为了写一个送货单,其中有list的数据导出。 ​ 本人目前在实习阶段,有错误请指正,如有侵权,联系删除。 一、...
  • easyexcel导出

    2022-05-17 10:45:03
    easyexcel导出
  • Java使用EasyExcel导出excel文件出现文件格式不匹配问题
  • EasyExcel导出模板

    2022-07-14 15:23:32
    } catch (Exception e) { throw new BizBaseRuntimeException(BaseExceptionEnum.FAIL.code(), "导出模板失败"); } } /** * 设置请求头 * * @author lyk * @date 2022/7/14 15:37 * @param response HttpServlet...
  • 一、前言 小编最近接到一个导出Excel的需求,需求还是很简单的,只需要把表格展示的信息导出成Excel就可以了,也没有复杂的合并列什么的。 常见的导出Excel的技术: ...使用POI把查询的数据表数据导出到Excel中,一个
  • easyexcel导出文件(多个sheet导出)

    千次阅读 2021-11-22 14:22:42
    <dependency> <groupId>.../groupId>...easyexcel</artifactId> <version>3.0.5</version> </dependency> 单个sheet @RequestMapping("/excelTest") .
  • springboot继承easyexcel实现指定列的导出功能
  • } @Override public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List list, Cell cell, Head head, Integer integer, Boolean aBoolean) { } } EasyExcel....
  • -- 阿里开源EXCEL 数据表导出--> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.0-beta2</version> </...
  • EasyExcel组件快速入门:导出Excel文件
  • 1、引入easyexcel依赖 !-- 阿里开源easyexcel--> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.0-beta2</...
  • EasyExcel导出

    2021-12-15 10:28:37
    * excel 流导出(需返回前端指定信息时调用该方法) * * @param response 输出流 * @param fileName 文件名前缀 * @param exportData 导出数据 * @param clazz Class对象 * @throws IOException 异常 */ ...
  • alibaba easyexcel导出

    2021-09-30 14:09:21
    alibaba easyexcel导出 ​   excel框架选用的时alibaba easyexcel。 ​   最近有个新的需求,导出文件时,需要根据某一列的值来做导出颜色的处理,当这列的值=指定值时,要求这一整列都要变为红色。 看了下源码...
  • 最详细入门EasyExcelEasyExcel如此简单
  • 使用easyexcel导出excel表格

    千次阅读 2022-04-20 09:44:00
    想要将数据使用excel表格导出,可以使用easyexcel pom.xml <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.0.5</...
  • easyExcel导出excel时指定列样式

    千次阅读 2020-12-01 20:55:09
    java POI生成excel设置列格式并写入文件 SpringBoot项目 easyexcel 给单元格设置格式,通过自定义注解方式实现对每一列格式的精确控制 java使用poi自定义excel标题头并导出(springmvc+poi) springboot+poi导出指定...
  • easyExcel导出通用方法

    2021-10-11 19:07:08
    easyExcel导出通用方法 开箱即用 导出效果 导出通用方法 ```java @Slf4j public class EasyExcelExport { /** * EasyExcel输出通用 * * @param response * @param title * @param companyName * @param ...
  • 在java处理excel方便从简单的实现功能自己封装工具类,一路走了好多,阿里的easyExcel对POI的封装更加精简这里介绍一下简单使用。
  • 1.1 EasyExcel封装类 package com.example.utils.easyexcel; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.Head; import ...
  • 第一步:添加easyExcel依赖 <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.2</version> </dependency> ...
  • 第一步导入所需依赖: ... } 以上通过EasyExcel导出excel文件并转为PDF或者图片以及其他格式,是总结了其他博主的知识点实现的,记录一下,方便后续使用与改进。
  • /** * 通用导出 * * @param list 数据源(用于生成excel表的数据) * @param response * @param clazz 对象类型(用于生成excel的表头) */ public void fileExport(List<?> list, HttpServletResponse response, ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,641
精华内容 656
关键字:

easyexcel导出到指定文件