一键导出excel功能(JAVA使用OPI实现excel导出)(SpringBoot)

E!RP系统浏览器端一键导出功能
在这里插入图片描述

  1. pom添加坐标
<!--poi(导出excel)-->
 <dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi</artifactId>
     <version>3.9</version>
 </dependency>
  1. html中添加导出标签
<a type="button" class="btn btn-default" href="/common/export">导出</a>
  1. resources可添加excel模板
    在这里插入图片描述
    在这里插入图片描述4. 编写controller代码
package com.sierte.phone.controller;

import com.sierte.phone.pojo.PMain;
import com.sierte.phone.service.PMainService;
import com.sierte.phone.util.DateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@Controller
@RequestMapping("common")
public class CommonController {

    @Autowired
    private PMainService pMainService;

    /**
     * 导出至excel
     * @return
     */
    @RequestMapping("export")
    public String exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {

        List<PMain> pMainList = pMainService.findAllPMain();

        /*String webPath=request.getServletContext().getRealPath("/");*/
        String path = ClassUtils.getDefaultClassLoader().getResource("static/client_down_model.xls").getPath();

        Workbook wb = fillExcelDataWithTemplate(pMainList, path);

        export(response,wb,"手机信息.xls");
        return null;
    }

    /**
     * @param templateFileUrl
     *            excel模板的路径 /admin/page/JYZ/client/client_info.xls
     * @return
     */
    public static Workbook fillExcelDataWithTemplate(List<PMain> list ,String templateFileUrl) {

        Workbook wb = null ;
        try {
            POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(templateFileUrl));
            wb = new HSSFWorkbook(fs);
            // 取得 模板的 第一个sheet 页
            Sheet sheet = wb.getSheetAt(0);
            // 拿到sheet页有 多少列
            int cellNums = sheet.getRow(0).getLastCellNum();
            // 从第2行 开搞    下标1  就是第2行
            int rowIndex = 1;
            Row row ;
            for(PMain pMain : list){
                row = sheet.createRow(rowIndex);
                rowIndex ++;
                row.createCell(0).setCellValue(pMain.getId());
                row.createCell(1).setCellValue(pMain.getPhone());
                row.createCell(2).setCellValue(pMain.getName());
                row.createCell(3).setCellValue(pMain.getPosition1());
                row.createCell(4).setCellValue(pMain.getPosition2());
                row.createCell(5).setCellValue(pMain.getAccount());
                row.createCell(6).setCellValue(pMain.getChange_count());
                row.createCell(7).setCellValue(pMain.getUpdate_count());
                row.createCell(8).setCellValue(DateUtil.formatDate(pMain.getStart_time(), "yyyy-MM-dd"));
                row.createCell(9).setCellValue(DateUtil.formatDate(pMain.getEnd_time(), "yyyy-MM-dd"));
                row.createCell(10).setCellValue(DateUtil.formatDate(pMain.getChange_time(), "yyyy-MM-dd"));
                row.createCell(11).setCellValue(pMain.getExplain());
                row.createCell(12).setCellValue(pMain.getImei());
                if (pMain.getStatus().equals("0")) {
                    row.createCell(13).setCellValue("闲置");
                } else if (pMain.getStatus().equals("1")) {
                    row.createCell(13).setCellValue("在用");
                } else if (pMain.getStatus().equals("2")) {
                    row.createCell(13).setCellValue("异常");
                } else if (pMain.getStatus().equals("3")) {
                    row.createCell(13).setCellValue("注销");
                }

                /*row.createCell(1).setCellValue(client.getBianhao());
                row.createCell(2).setCellValue(client.getName());
                row.createCell(3).setCellValue(client.getPhone());
                row.createCell(4).setCellValue(client.getRemark());
                row.createCell(5).setCellValue(DateUtil.formatDate(client.getCreateDateTime(), "yyyy-MM-dd HH:mm:ss"));
                */
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    /**
     * 导出
     * @param response
     * @param wb
     * @param fileName
     * @throws Exception
     */
    public  void export(HttpServletResponse response,Workbook wb,String fileName)throws Exception{
        response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("utf-8"),"iso8859-1"));
        response.setContentType("application/ynd.ms-excel;charset=UTF-8");
        OutputStream out=response.getOutputStream();
        wb.write(out);
        out.flush();
        out.close();
    }
}


  1. 日期格式化工具类
package com.sierte.phone.util;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {

    /**
     * yyyyMMdd hhmmssSSS
     * 日期对象转字符串
     */
    public static String formatDate(Date date, String format){
        String result="";
        SimpleDateFormat sdf=new SimpleDateFormat(format);
        if(date!=null){
            result=sdf.format(date);
        }
        return result;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Apache POI 导出 Excel,你需要进行以下步骤: 1. 首先,确保你的项目中已经包含了 Apache POI 的相关库文件。你可以通过 Maven 或 Gradle 等构建工具添加相关依赖。 2. 创建一个新的 Excel 文档对象: ```java Workbook workbook = new XSSFWorkbook(); // 创建一个新的 .xlsx 文件 // 或者使用以下代码创建一个 .xls 文件 // Workbook workbook = new HSSFWorkbook(); ``` 3. 创建一个工作表并设置其名称: ```java Sheet sheet = workbook.createSheet("Sheet1"); ``` 4. 创建行和单元格,并设置数据: ```java Row row = sheet.createRow(0); // 创建第一行 Cell cell = row.createCell(0); // 创建第一列 cell.setCellValue("Hello, World!"); // 设置单元格的值 ``` 5. 格式化单元格(可选): ```java CellStyle style = workbook.createCellStyle(); style.setFillForegroundColor(IndexedColors.GREEN.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); cell.setCellStyle(style); ``` 6. 保存 Excel 文件: ```java try (FileOutputStream outputStream = new FileOutputStream("output.xlsx")) { workbook.write(outputStream); } ``` 以上代码将创建一个名为 "output.xlsx" 的 Excel 文件,并将 "Hello, World!" 写入第一行第一列的单元格。 请注意,这只是一个简单的示例,你可以根据自己的需求进行更复杂的操作,例如添加多个工作表、设置单元格格式、合并单元格等等。此外,还可以使用 Apache POI 的其他类和方法来读取和处理现有的 Excel 文件。 希望这可以帮助到你!如果你有任何进一步的问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值