springmvc实现excel文件导出

记一次springmvc实现excel文件导出,代码直接复制简单修改即可用。

第一步:excel pom依赖包

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.11</version>
</dependency>

第二步:controller层

// 导出excel相关
@RequestMapping("/orderStaticExcel")
public void excelOrderStatic(@RequestBody FinanceReportsCommonRequest financeReportsCommonRequest, HttpServletResponse response) throws IOException {
    // 设置response参数,可以打开下载页面
    response.reset();
    response.setContentType("application/vnd.ms-excel;charset=utf-8");
    response.setHeader("Content-Disposition", "attachment;filename=" + new String(("订单统计" + ".xls").getBytes(), StandardCharsets.ISO_8859_1));
    ServletOutputStream out = response.getOutputStream();
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        bis = new BufferedInputStream(new ByteArrayInputStream(omsReportStatisticsService.excelByte(financeReportsCommonRequest)));
        bos = new BufferedOutputStream(out);
        byte[] buff = new byte[2048];
        int bytesRead;
        // Simple read/write loop.
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
    } catch (IOException e) {
        logger.error("出现其他异常:", e);
    } finally {
        if (bis != null) {
            bis.close();
        }
        if (bos != null) {
            bos.close();
        }
    }
}

第三步:接口层

public interface OmsReportStatisticsService {
    byte[] excelByte(FinanceReportsCommonRequest financeReportsCommonRequest);
}

第四步:接口实现层

@Service("omsReportStatisticsServiceImpl")
public class OmsReportStatisticsServiceImpl implements OmsReportStatisticsService {
    private static final Logger logger = LoggerFactory.getLogger(OmsReportStatisticsServiceImpl.class);

    @Override
    public byte[] excelByte(FinanceReportsCommonRequest financeReportsCommonRequest) {
        ByteArrayOutputStream baos = null;
        try {
            // excel标题
            String[] title = {"订单号", "客户手机号", "支付日期", "实际支付日期", "期数", "应付租金", "已付租金", "应付增值费用","实付增值费用", "应付保险金额", "实付保险金额", "应付运费", "实付运费", "折扣金额", "实际折扣金额", "应付其他费用", "实付其他费用","应减免金额", "实际减免金额", "应付罚息", "实付罚息", "应付押金", "实付押金", "押金转租金", "应付买断费", "实付买断费","用户已支付(不包含押金)", "用户已支付(包含押金)"};

            // 列的宽度
            int[] length = {
                20, 20, 20, 20, 20, 20, 20,
                20, 20, 20, 20, 20, 20, 20,
                20, 20, 20, 20, 20, 20, 20,
                20, 20, 20, 20, 20, 20, 20};

            // sheet名
            String sheetName = "订单统计报表";

            String[][] content = null;

            PageInfo<OrderStaticReportResultDTO> pageInfo = this.orderFinanceStaticReport(financeReportsCommonRequest);
            content = new String[title.length][title.length];

            for (int i = 0; i < pageInfo.getList().size(); i++) {
                OrderStaticReportResultDTO repayBalance = pageInfo.getList().get(i);
                content[i][0] = repayBalance.getOrderNo();
                content[i][1] = repayBalance.getMobilePhoneNo();
                content[i][2] = repayBalance.getPayDate();
                content[i][3] = repayBalance.getFinishDate();
                content[i][4] = repayBalance.getCnt().toString();
                content[i][5] = repayBalance.getPayRentAmt().toString();
                content[i][6] = repayBalance.getActualPayRentAmt().toString();
                content[i][7] = repayBalance.getPayRaiseAmt().toString();
                content[i][8] = repayBalance.getActualPayRaiseAmt().toString();
                content[i][9] = repayBalance.getPayInsureAmt().toString();
                content[i][10] = repayBalance.getActualPayInsureAmt().toString();
                content[i][11] = repayBalance.getPayLogisticsAmt().toString();
                content[i][12] = repayBalance.getActualPayLogisticsAmt().toString();
                content[i][13] = repayBalance.getPayDiscountAmt().toString();
                content[i][14] = repayBalance.getActualPayDiscountAmt().toString();
                content[i][15] = repayBalance.getPayOtherAmt().toString();
                content[i][16] = repayBalance.getActualPayOtherAmt().toString();
                content[i][17] = repayBalance.getPayReductionAmt().toString();
                content[i][18] = repayBalance.getActualPayReductionAmt().toString();
                content[i][19] = repayBalance.getPayFineAmt().toString();
                content[i][20] = repayBalance.getActualPayFineAmt().toString();
                content[i][21] = repayBalance.getPayDepositAmt().toString();
                content[i][22] = repayBalance.getActualPayDepositAmt().toString();
                content[i][23] = repayBalance.getLimitDepositAmt().toString();
                content[i][24] = repayBalance.getBuyoutAmt().toString();
                content[i][25] = repayBalance.getActualBuyoutAmt().toString();
                content[i][26] = repayBalance.getCustActualExcludeDepositAmt().toString();
                content[i][27] = repayBalance.getCustActualIncludeDepositAmt().toString();
            }


            logger.info("to there !");

            // 创建HSSFWorkbook
            HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null, length);
            baos = new ByteArrayOutputStream();
            wb.write(baos);
            logger.info("生成文件");
            baos.flush();
            //            return new ByteArrayInputStream(baos.toByteArray());
            return baos.toByteArray();
        } catch (Exception e) {
            logger.error("generateStreamByTrans err", e);
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    logger.error("close baos err", e);
                }
            }
        }
        return null;
    }
}    

第五、ExcelUtils工具类

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

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class ExcelUtils {
    /**
     * 导出Excel
     *
     * @param sheetName sheet名称
     * @param title     标题
     * @param values    内容
     * @param wb        HSSFWorkbook对象
     * @return HSSFWorkbook
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook wb, int[] length) {
        // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
        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 titleStyle = wb.createCellStyle();
        titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        titleStyle.setFillForegroundColor(HSSFColor.WHITE.index);
        // 创建一个居中格式
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFCellStyle cellStyle = wb.createCellStyle();
        // 创建一个居中格式
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        //声明列对象
        HSSFCell cell = null;

        //创建标题
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(titleStyle);
            sheet.setColumnWidth(i, length[i] * 256);
        }
        if (values != null && values.length > 0) {
            //创建内容
            for (int i = 0; i < values.length; i++) {
                row = sheet.createRow(i + 1);
                for (int j = 0; j < values[i].length; j++) {
                    //将内容按顺序赋给对应的列对象
                    cell = row.createCell(j);
                    cell.setCellValue(values[i][j]);
                    cell.setCellStyle(cellStyle);
                }
            }
        }
        return wb;
    }

    /**
     * 导出多个sheet的Excel表
     *
     * @param sheetNames sheet名称
     * @param titles     标题
     * @param values     内容
     * @param wb         HSSFWorkbook对象
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbookWithMoreSheet(List<String> sheetNames, List<String[]> titles, List<String[][]> values, HSSFWorkbook wb, List<int[]> lengths) {

        // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
        if (wb == null) {
            wb = new HSSFWorkbook();
        }
        for (int m = 0; m < sheetNames.size(); m++) {
            // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet(sheetNames.get(m));

            // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
            HSSFRow row = sheet.createRow(0);

            HSSFRow englishRow = sheet.createRow(1);

            // 第四步,创建单元格,并设置值表头 设置表头居中
            HSSFCellStyle titleStyle = wb.createCellStyle();
            titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            titleStyle.setFillForegroundColor(HSSFColor.ROYAL_BLUE.index);
            titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

            HSSFCellStyle cellStyle = wb.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

            //声明列对象
            HSSFCell cell = null;

            int[] length = lengths.get(m);
            String[] title = titles.get(m);
            String[] englishTitle = titles.get(m + 2);

            //创建标题
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(titleStyle);
                sheet.setColumnWidth(i, length[i] * 256);
            }

            //创建标题
            for (int i = 0; i < englishTitle.length; i++) {
                cell = englishRow.createCell(i);
                cell.setCellValue(englishTitle[i]);
                cell.setCellStyle(titleStyle);
                sheet.setColumnWidth(i, length[i] * 256);
            }


            if (values != null) {
                String[][] value = values.get(m);
                //创建内容
                if (value != null && value.length > 0) {
                    for (int i = 0; i < value.length; i++) {
                        row = sheet.createRow(i + 2);
                        for (int j = 0; j < value[i].length; j++) {
                            //将内容按顺序赋给对应的列对象
                            cell = row.createCell(j);
                            cell.setCellValue(value[i][j]);
                            cell.setCellStyle(cellStyle);
                        }
                    }
                }
            }


        }
        return wb;
    }
    

    /**
     * @Author jason
     * @Description 发送响应流方法
     * @UpdateRemark: 修改内容
     * @Param [response, fileName]
     **/
    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                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();
        }
    }
}

原文地址:https://www.cnblogs.com/jasonboren/p/14762908.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


开发过程中是不可避免地会出现各种异常情况的,例如网络连接异常、数据格式异常、空指针异常等等。异常的出现可能导致程序的运行出现问题,甚至直接导致程序崩溃。因此,在开发过程中,合理处理异常、避免异常产生、以及对异常进行有效的调试是非常重要的。 对于异常的处理,一般分为两种方式: 编程式异常处理:是指在代
说明:使用注解方式实现AOP切面。 什么是AOP? 面向切面编程,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。 通俗描述:不通过修改源代码方式,在主干功能里面添加新功能。 AOP底层使用动态代理。 AOP术语 连接点
Spring MVC中的拦截器是一种可以在请求处理过程中对请求进行拦截和处理的机制。 拦截器可以用于执行一些公共的操作,例如日志记录、权限验证、数据转换等。在Spring MVC中,可以通过实现HandlerInterceptor接口来创建自定义的拦截器,并通过配置来指定拦截器的应用范围和顺序。 S
在 JavaWeb 中,共享域指的是在 Servlet 中存储数据,以便在同一 Web 应用程序的多个组件中进行共享和访问。常见的共享域有四种:ServletContext、HttpSession、HttpServletRequest、PageContext。 ServletContext 共享域:
文件上传 说明: 使用maven构建web工程。 使用Thymeleaf技术进行服务器页面渲染。 使用ResponseEntity实现下载文件的功能。 @Controller public class FileDownloadAndUpload { @GetMapping(&quot;/file/d
创建初始化类,替换web.xml 在Servlet3.0环境中,Web容器(Tomcat)会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器。 Spring提供了这个接口的实现,名为SpringS
在 Web 应用的三层架构中,确保在表述层(Presentation Layer)对数据进行检查和校验是非常重要的。正确的数据校验可以确保业务逻辑层(Business Logic Layer)基于有效和合法的数据进行处理,同时将错误的数据隔离在业务逻辑层之外。这有助于提高系统的健壮性、安全性和可维护
什么是事务? 事务(Transaction)是数据库操作最基本单元,逻辑上一组操作,要么都成功,要么都失败,如果操作之间有一个失败所有操作都失败 。 事务四个特性(ACID) 原子性 一组操作要么都成功,要么都失败。 一致性 一组数据从事务1合法状态转为事务2的另一种合法状态,就是一致。 隔离性 事
什么是JdbcTemplate? Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作。 准备工作 引入jdbcTemplate的相关依赖: 案例实操 创建jdbc.properties文件,配置数据库信息 jdbc.driver=com.mysql.cj.
SpringMVC1.MVC架构MVC是模型(Model)、视图(View)、控制器(Controller)的简写,是一种软件设计规范是将业务逻辑、数据、显示分离的方法来写代码MVC主要作用是:降低了视图和业务逻辑之间的双向耦合MVC是一个架构模型,不是一种设计模式。1.model(模型)数据模型,提供要展示的数据,因此包
SpringMVC学习笔记1.SpringMVC应用1.1SpringMVC简介​SpringMVC全名叫SpringWebMVC,是⼀种基于Java的实现MVC设计模型的请求驱动类型的轻量级Web框架,属于SpringFrameWork的后续产品。​MVC全名是ModelViewController,是模型(model)-视图(view)-控制器(co
11.1数据回显基本用法数据回显就是当用户数据提交失败时,自动填充好已经输入的数据。一般来说,如果使用Ajax来做数据提交,基本上是没有数据回显这个需求的,但是如果是通过表单做数据提交,那么数据回显就非常有必要了。11.1.1简单数据类型简单数据类型,实际上框架在这里没有
一、SpringMVC简介1、SpringMVC中重要组件DispatcherServlet:前端控制器,接收所有请求(如果配置/不包含jsp)HandlerMapping:解析请求格式的.判断希望要执行哪个具体的方法.HandlerAdapter:负责调用具体的方法.ViewResovler:视图解析器.解析结果,准备跳转到具体的物
1.它们主要负责的模块Spring主要应用于业务逻辑层。SpringMVC主要应用于表现层。MyBatis主要应用于持久层。2.它们的核心Spring有三大核心,分别是IOC(控制反转),DI(依赖注入)和AOP(面向切面编程)。SpringMVC的核心是DispatcherServlet(前端控制器)。MyBatis的核心是ORM(对
3.注解开发Springmvc1.使用注解开发要注意开启注解支持,2.注解简化了,处理映射器和处理适配器,只用去管视图解析器即可案例代码:1.web.xml,基本不变可以直接拿去用<!--调用DispatcherServlet--><servlet><servlet-name>springmvc</servlet-name>
拦截器概述SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现特定的功能。**过滤器与拦截器的区别:**拦截器是AOP思想的具体应用。过滤器servlet规范中的一部分,任何javaweb工程都可以使用
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:xsi="
学习内容:1、SSH&SSM2、Spring3、Struts2&SpringMVC4、Hibernate&MyBatis学习产出:1.SSH和SSM都是有Spring框架的,他们两个差不多。2.Spring分为四个模块,持久层,表示层,检测层,还有核心层,核心层分为2个关键核心功能。分别为,控制反转(IOC),依赖注入(DI),和面向切面编程
一、SpringMVC项目无法引入js,css的问题具体原因是css和js等被SpringMVC拦截了:解决方案:在spring-mvc.xml中配置<mvc:default-servlet-handler/><?xmlversion="1.0"encoding="UTF-8"?><beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
开发环境:Eclipse/MyEclipse、Tomcat8、Jdk1.8数据库:MySQL前端:JavaScript、jQuery、bootstrap4、particles.js后端:maven、SpringMVC、MyBatis、ajax、mysql读写分离、mybatis分页适用于:课程设计,毕业设计,学习等等系统介绍