导出Excel工具类

1、工具类源码

package com.mkaq.core.util;

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

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by z on 2018/12/12.
 */

public class ExcelExport {
    /**
     * 导出Excel
     *
     * @param fileName  Excel表格名称
     * @param sheetName sheet名称
     * @param title     标题
     * @param values    数据内容
     * @param wb        HSSFWorkbook对象
     * @return
     */
    public static void getHSSFWorkbook(String fileName, String sheetName, String[] title, String[][] values, HSSFWorkbook wb, HttpServletResponse res) {

        // 第一步,创建一个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 style = wb.createCellStyle();
        style.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(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]);
            }
        }

/**----------------------------------以上已经将所有数据放入 HSSFWorkbook 中--------------------------**/

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            wb.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }

        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);

        // 设置response参数,可以打开下载页面
        res.reset();
        res.setContentType("application/vnd.ms-excel;charset=utf-8");
        try {
            res.setHeader("Content-Disposition", "attachment;filename="
                    + new String((fileName).getBytes(), "iso-8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ServletOutputStream out = null;
        try {
            out = res.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;

            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

2、使用(准备好工具类中所需要的参数之后,直接调用工具类方法)

package org.platform4j.controller;

import com.mkaq.core.util.ExcelExport;
import org.platform4j.model.griddata.GridDataBase_Org;
import org.platform4j.model.griddata.GridDataEmp;
import org.platform4j.model.griddata.GridDataUserinfo;
import org.platform4j.model.kingcenum.UserType;
import org.platform4j.service.DepartmentService;
import org.platform4j.service.EmpService;
import org.platform4j.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
public class ControllerExcelExport {

    //查询部门的服务
    @Autowired
    private DepartmentService departmentService;

    //导出部门的Excel
    @RequestMapping(value = "/exportDepartment")
    public void exportDepartment(HttpServletResponse res, String fOrgID) {
        //获取部门数据
        GridDataBase_Org chilidOrgAll = departmentService.getChilidOrgAll(fOrgID, null, false, 10000, 1);

        //Excel标题
        String[] title = {"部门名称", "上级部门", "负责人"};

        //excel文件名
        String fileName = "部门信息表" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "部门信息表";

        String[][] values = new String[chilidOrgAll.getRows().size()][3];
        for (int i = 0; i < chilidOrgAll.getRows().size(); i++) {
            if (null != chilidOrgAll.getRows().get(i).getFOrg_Name()) {
                values[i][0] = chilidOrgAll.getRows().get(i).getFOrg_Name().toString();//部门名称
            } else {
                values[i][0] = "";
            }

            if (null != chilidOrgAll.getRows().get(i).getfParent_Name()) {
                values[i][1] = chilidOrgAll.getRows().get(i).getfParent_Name().toString();//上级部门
            } else {
                values[i][1] = "";
            }

            if (null != chilidOrgAll.getRows().get(i).getFOrg_Leader_Name()) {
                values[i][2] = chilidOrgAll.getRows().get(i).getFOrg_Leader_Name().toString();//负责人
            } else {
                values[i][2] = "";
            }
        }

        //导出Excel表格方法
        ExcelExport.getHSSFWorkbook(fileName, sheetName, title, values, null, res);

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot导出Excel工具类可以使用EasyExcel库来实现。首先,需要在项目的pom.xml文件中引入EasyExcel的依赖。可以使用以下代码将依赖添加到pom.xml文件中: ```xml <!-- 导出excel --> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>1.1.2-beta5</version> </dependency> ``` 接下来,在Controller中编写导出Excel的方法。可以使用以下代码作为参考: ```java /** * 学生信息导出 */ @RequestMapping(value = "api/url", method = RequestMethod.POST) public void studentExportExcel(HttpServletResponse response, @RequestBody StudentBean bean) { // 查询需要导出的数据 List<StudentExportBean> studentExportList = studentDao.studentExport(bean); // 设置表头 String\[\] headers = new String\[\]{"年级", "学号", "姓名", "专业", "二级学院", "联系方式", "性别"}; // 设置导出文件名 String fileName = "学生信息表"; // 调用Excel导出工具类进行导出 ExcelExport.export(response, studentExportList, headers, fileName, 6); } ``` 在上述代码中,首先从数据库中查询需要导出的学生信息数据,然后设置表头和导出文件名。最后,调用ExcelExport.export方法进行导出。请注意,ExcelExport是一个自定义的工具类,用于实现Excel导出的具体逻辑。 希望以上信息对您有所帮助。 #### 引用[.reference_title] - *1* [SpringBoot实现excel表格导出](https://blog.csdn.net/Hello_mengkebao/article/details/119597062)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [SpringBoot导出Excel工具类](https://blog.csdn.net/qq_41341640/article/details/109067688)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值