Java读写excel文件

最近在学习某马的外卖项目,需要使用Java读写excel文件。

  • 导入依赖
xml 复制代码
<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi</artifactId>
 <version>3.16</version>
</dependency>
<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi-ooxml</artifactId>
 <version>3.16</version>
</dependency>
  • 读取excel
java 复制代码
FileInputStream in = new FileInputStream(new File("D:\\itcast.xlsx"));
//通过输入流读取指定的Excel文件XSSFWorkbook excel = new XSSFWorkbook(in);
//获取Excel文件的第1个Sheet页
XSSFSheet sheet = excel.getSheetAt(0);
//获取Sheet页中的最后一行的行号
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i <= lastRowNum; i++) {
     //获取Sheet页中的行
     XSSFRow titleRow = sheet.getRow(i);
     //获取行的第2个单元格
     XSSFCell cell1 = titleRow.getCell(1);
     //获取单元格中的文本内容
     String cellValue1 = cell1.getStringCellValue();
     //获取行的第3个单元格
     XSSFCell cell2 = titleRow.getCell(2);
     //获取单元格中的文本内容
     String cellValue2 = cell2.getStringCellValue();
     System.out.println(cellValue1 + " " +cellValue2);
     }
     //关闭资源
     in.close();
     excel.close();
  • 写excel
java 复制代码
//在内存中创建一个Excel文件对象
XSSFWorkbook excel = new XSSFWorkbook();
//创建Sheet页
XSSFSheet sheet = excel.createSheet("itcast");
//在Sheet页中创建行,0表示第1行
XSSFRow row1 = sheet.createRow(0);
//创建单元格并在单元格中设置值,单元格编号也是从0开始,1表示第2个单元格
row1.createCell(1).setCellValue("姓名");
row1.createCell(2).setCellValue("城市");
XSSFRow row2 = sheet.createRow(1);
row2.createCell(1).setCellValue("张三");
row2.createCell(2).setCellValue("北京");
XSSFRow row3 = sheet.createRow(2);
row3.createCell(1).setCellValue("李四");
row3.createCell(2).setCellValue("上海");
FileOutputStream out = new FileOutputStream(new File("D:\\itcast.xlsx"));
//通过输出流将内存中的Excel文件写入到磁盘上
excel.write(out);
//关闭资源out.flush();
out.close();
excel.close();
  • 下载excel
java 复制代码
    /**
     * 导出excel表
     * @param httpServletResponse
     */
    @Override
    public void exportData(HttpServletResponse httpServletResponse) throws IOException {
        //打开文件
        InputStream in=  this.getClass().getClassLoader().getResourceAsStream("template/template.xlsx");
        //创键excel对象
        XSSFWorkbook excel=new XSSFWorkbook(in);
        XSSFSheet sheet=excel.getSheetAt(0);
        //创建日期
        LocalDate end=LocalDate.now().plusDays(-1);
        LocalDate begin=LocalDate.now().plusDays(-30);
        sheet.getRow(1).getCell(1).setCellValue(begin+"---"+end);
        //读取概览数据
        BusinessDataVO businessDataVO=this.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX));
        sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
        sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
        sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
        //遍历每一天
        int cnt=7;
        while(!begin.equals(end)){
            BusinessDataVO businessData=this.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(begin,LocalTime.MAX));
            sheet.getRow(cnt).getCell(1).setCellValue(String.valueOf(begin));
            sheet.getRow(cnt).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(cnt).getCell(3).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(cnt).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(cnt).getCell(5).setCellValue(businessData.getUnitPrice());
            sheet.getRow(cnt).getCell(6).setCellValue(businessData.getNewUsers());
            begin=begin.plusDays(1);
            cnt++;
        }
        //最后一天
        BusinessDataVO businessData=this.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(begin,LocalTime.MAX));
        sheet.getRow(cnt).getCell(1).setCellValue(String.valueOf(begin));
        sheet.getRow(cnt).getCell(2).setCellValue(businessData.getTurnover());
        sheet.getRow(cnt).getCell(3).setCellValue(businessData.getValidOrderCount());
        sheet.getRow(cnt).getCell(4).setCellValue(businessData.getOrderCompletionRate());
        sheet.getRow(cnt).getCell(5).setCellValue(businessData.getUnitPrice());
        sheet.getRow(cnt).getCell(6).setCellValue(businessData.getNewUsers());
        begin=begin.plusDays(1);
        cnt++;

        //设置content-type
        httpServletResponse.setContentType("application/octet-stream");
        //设置文件头
        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("example.xlsx", "UTF-8"));
        //获取输出流
        ServletOutputStream out=httpServletResponse.getOutputStream();
        excel.write(out);
        //关闭流
        in.close();
        out.close();
        excel.close();
    }
相关推荐
liwulin05067 小时前
【PYTHON】使用Selenium + ChromeDriver以及XPATH语法
开发语言·python·selenium
szephyr7 小时前
腾讯云 ADP 智能体的 Skills 版本回滚总是回到旧配置,是缓存没清还是版本管理没开?
java·缓存·腾讯云
JavaPub-rodert7 小时前
我又把自己的 Go 后台管理系统升级了一遍:文件管理、2GB 上传、私有文件预览、Docker 镜像全安排上了
开发语言·docker·golang·shiyuadmin
云烟成雨TD7 小时前
Micrometer 系列【39】链路追踪:入门案例 | 环境准备
java·云原生·链路追踪
chuan.bai7 小时前
Java RAG 实战(第 3 篇):从交互式聊天到多轮上下文
java·人工智能·macos·ai
动力 continue7 小时前
Python 元类与异常类:类的“制造工厂”与“报错定制师”
开发语言·python·制造
quantdash_cc7 小时前
基于 QuantDash 5 分钟 K 线的网格交易策略参数网格搜索寻优实战
android·开发语言·pandas·量化·quantdash
147API7 小时前
Python批量生成蒸馏数据,并发、重试、幂等和断点续跑
开发语言·jvm·python
青 春 记 忆7 小时前
零基础入门python04:用注册校验理解字典、集合和条件判断
开发语言·vscode·python·python3.11
952367 小时前
Sentinel
java·后端·spring·sentinel·springcloud