• 利用hutool导出Excel


    1、导入依赖

    		<dependency>
    			<groupId>cn.hutool</groupId>
    			<artifactId>hutool-all</artifactId>
    			<version>5.7.3</version>
    		</dependency>
    
    <!--		excel导出依赖-->
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi-ooxml</artifactId>
    			<version>4.1.2</version>
    		</dependency>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2、代码

    Apache POI既可以将数据写入Excel文件,也可以读取Excel文件中的数据,

    2.1 基于POI写入excel文件

     public static void write() throws IOException {
            // 在内存重创建一个excel对象
            XSSFWorkbook excel = new XSSFWorkbook();
            // 创建sheet页
            XSSFSheet sheet = excel.createSheet("itcast");
            // 在sheet页中创建行,0表示第1行
            XSSFRow row1 = sheet.createRow(0);
            // 创建单元格,row1.createCell()
            // 设置单元格值 setCellValue("姓名")
            row1.createCell(1).setCellValue("姓名");
            row1.createCell(2).setCellValue("城市");
    
    // 输出工作簿到文件或输出流
            FileOutputStream out = new FileOutputStream(new File("D:\\itcast.xlsx"));
            //通过输出流将内存中的Excel文件写入到磁盘上
            excel.write(out);
    
            out.flush();
            out.close();
            excel.close();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    2.2 读取excel文件

    public static void read() throws IOException {
            FileInputStream input = new FileInputStream(new File("D:\\itcast.xlsx"));
            XSSFWorkbook excel = new XSSFWorkbook(input);
            XSSFSheet sheet = excel.getSheetAt(0);
    
            int lastRowNum = sheet.getLastRowNum();
    
            for (int i=0;i<=lastRowNum;i++){
                XSSFRow row = sheet.getRow(i);  // 获取行
    
                XSSFCell cell1 = row.getCell(1); // 获取行的第2个单元格
                String cellValue1 = cell1.getStringCellValue();//获取单元格的文本内容
                XSSFCell cell2 = row.getCell(2);
                String cellValue2 = cell2.getStringCellValue();
    
    
                System.out.println(cellValue1+" "+cellValue2);
    
                input.close();
                excel.close();
    
    
            }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
  • 相关阅读:
    SpringBoot整合MyBatis从零开始
    迭代器模式
    【技术分享】接口幂等性:为什么你需要它?
    对外提供服务的方法
    [C++](10)C++的string类如何实现?
    电脑是怎样上网的 (二) 从网线到网络设备
    智慧实验室解决方案-最新全套文件
    Layui 表单设计器
    软件工程综合实践课程第一周作业(面向对象编程实验与继承与多态实验)
    数据结构 Map&Set(搜索)
  • 原文地址:https://blog.csdn.net/Mikon_0703/article/details/132803202