java如何导出Excel表格

第一步 准备工作

1.引入maven包

        <!-- excel工具 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.0</version>
        </dependency>

2.编写工具类

package com.zhshx.app.common.utils;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Excel 表的处理 下载的Excel版本是2007以及以后的版本--(2007/2010..)
 * 此工具类需要导入maven包
 * <!-- excel工具 -->
 * 		<dependency>
 * 			<groupId>org.apache.poi</groupId>
 * 			<artifactId>poi</artifactId>
 * 			<version>4.0.0</version>
 * 		</dependency>
 * 		<dependency>
 * 			<groupId>org.apache.poi</groupId>
 * 			<artifactId>poi-ooxml</artifactId>
 * 			<version>4.0.0</version>
 * 		</dependency>
 * @Author yimocha
 * @Date 2019/7/26 10:14
 * @Version 1.0
 **/
public class ExcelUtil {

    /**
     * 读取Excel模版
     * 此方法用于读取Excel模板 需要传入Excel存放在项目中的位置
     * 然后这个方法会根据模板创建一个execl工作对象
     * @param filePath
     * @return
     * @throws IOException
     * by yimocha
     */
    public static XSSFWorkbook readWorkBook(String filePath){
        XSSFWorkbook wb=null;
        InputStream is;
        //寻找目录读取文件
        File excelFile = new File(filePath);
        try {
            is = new FileInputStream(excelFile);
            wb = new XSSFWorkbook(is);
            if(wb==null){
                System.out.println("===========未读取到内容,请检查路径!===========");
                return null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("===========未找到文件!===========");
        }catch (IOException e) {
            e.printStackTrace();
            System.out.println("===========读取文件失败!===========");
        }
        return wb;
    }

    /**
     * 下载
     * 下载的Excel版本是2007以及以后的版本
     * 如果是xlsx,使用XSSFWorkbook
     * @param response
     * @throws Exception
     */
    public static void download(XSSFWorkbook wrkbook, HttpServletResponse response, String fileName){
        //输出Excel文件
        try {
            OutputStream output=response.getOutputStream();
            initResponse(response,fileName);
            wrkbook.write(output);
            output.close();
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("====下载Excel文件异常,异常信息:"+e.getMessage());
        }
    }

    /**
     * 初始化响应头,传入response 和 fileName(文件名)
     * .xlsx
     * @param response
     * @param fileName
     */
    private static void initResponse(HttpServletResponse response,String fileName){
        response.reset();
        fileName = URLEncoder.encode(fileName);
        response.setHeader("Content-disposition", "attachment; filename="+fileName+".xlsx");
        response.setContentType("application/msexcel");
    }

    /**
     * zip打包下载
     * @param response
     * @param excels
     * @param fileNameList
     */
    public static void downFileByStream(HttpServletResponse response, List<XSSFWorkbook> excels, List<String> fileNameList){
        try {
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename="+fileNameList.get(0)+"_"+fileNameList.get(fileNameList.size()-1)+".zip");
            response.setContentType("application/msexcel");
            ZipOutputStream zipOut = new ZipOutputStream(toClient);
            for(int i=0;i<excels.size();i++){
                ZipEntry entry = new ZipEntry(fileNameList.get(i)+".xls");
                zipOut.putNextEntry(entry);
                excels.get(i).write(zipOut);
            }
            zipOut.flush();
            zipOut.close();
        }catch (Exception e){
            System.out.println("======downFileByStream==========下载文件流失败");
        }
    }

    /**
     * 获得项目路径
     * @return
     * by yimocha
     */
    public static String getProjectPath(){
        return System.getProperty("user.dir");
    }

    /**
     * excel文件的路径 只需要传入【文件名】(order.xlsx)
     * 此方法已经做了约定的处理,需要在项目的这个路径下 src/main/resources/excel 存放Excel文档的模板
     * 在使用时,直接调用这个方法 就可以 获得 前路径 最后加上自己的想用的Excel模板的文件名
     * 调用这个方法getExcelPath("order.xlsx");返回如下路径
     *
     * 项目路径/src/main/resources/excel/order.xlsx
     *
     * @param fileName
     * @return
     */
    public static String getExcelPath(String fileName){
        String filePath = "/src/main/resources/excel/";
        return ExcelUtil.getProjectPath()+filePath+fileName;
    }

}

3.放入模板 - 名字可以自己取
在这里插入图片描述

4.编写Controller类使用

package com.zhshx.app.admin;

import com.zhshx.app.common.utils.ExcelUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author yimocha
 * @Version 1.0
 **/
@Controller
@RequestMapping("/excel")
public class ExcelController {


    @RequestMapping("/outExcel.do")
    public void testExcel(HttpServletResponse response,String Condition){
            XSSFWorkbook workbook = ExcelUtil.readWorkBook(ExcelUtil.getExcelPath("moban.xlsx"));
            ExcelUtil.download(workbook,response,"test");
    }

}

6.浏览器下载
在这里插入图片描述
基础部分请到这里
java导出Excel基础知识了解

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值