浏览器生成Excel文件 ,Apache POI 使用方法及示例

Apache POI 是 Apache 软件基金会的开源项目,它提供 API 用于读取和写入 Microsoft Office 格式的文件,如 Excel、Word 等。在 Spring Boot 应用中,结合使用 Apache POI 可以方便地处理 Excel 文件

一 引入依赖:
XML 复制代码
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

二 读取Excel示例:

java 复制代码
import org.apache.poi.ss.usermodel.*; // 导入Apache POI的通用接口  
import org.apache.poi.xssf.usermodel.XSSFWorkbook; // 导入用于处理.xlsx文件的类  
  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
  
public class ExcelReader {  
  
    public static void main(String[] args) {  
        try (FileInputStream fis = new FileInputStream(new File("path/to/your/excel/file.xlsx"))) {  
            // 创建一个工作簿对象,从输入流中读取Excel文件  
            Workbook workbook = new XSSFWorkbook(fis);  
            // 获取第一个工作表  
            Sheet sheet = workbook.getSheetAt(0);  
  
            // 遍历工作表中的所有行  
            for (Row row : sheet) {  
                // 遍历行中的所有单元格  
                for (Cell cell : row) {  
                    // 获取单元格的值,并打印  
                    String cellValue = getCellValueAsString(cell);  
                    System.out.print(cellValue + "\t"); // \t 是制表符,用于分隔单元格内容  
                }  
                System.out.println(); // 每行结束后换行  
            }  
  
            // 关闭工作簿  
            workbook.close();  
        } catch (IOException e) {  
            // 如果发生IO异常,打印堆栈跟踪  
            e.printStackTrace();  
        }  
    }  
  
    /**  
     * 根据单元格类型获取单元格的值,并返回字符串表示  
     *  
     * @param cell 要获取值的单元格  
     * @return 单元格值的字符串表示  
     */  
    private static String getCellValueAsString(Cell cell) {  
        switch (cell.getCellType()) {  
            case STRING:  
                return cell.getStringCellValue(); // 字符串类型直接返回  
            case NUMERIC:  
                if (DateUtil.isCellDateFormatted(cell)) {  
                    return DateUtil.formatCellValueToDate(cell).toString(); // 日期类型格式化为字符串  
                } else {  
                    return Double.toString(cell.getNumericCellValue()); // 数字类型转换为字符串  
                }  
            case BOOLEAN:  
                return Boolean.toString(cell.getBooleanCellValue()); // 布尔类型转换为字符串  
            case FORMULA:  
                return cell.getCellFormula(); // 公式类型返回公式字符串  
            default:  
                return ""; // 其他类型返回空字符串  
        }  
    }  
}

三 写入Excel示例:

java 复制代码
import org.apache.poi.ss.usermodel.*; // 导入Apache POI的通用接口  
import org.apache.poi.xssf.usermodel.XSSFWorkbook; // 导入用于处理.xlsx文件的类  
  
import java.io.FileOutputStream;  
import java.io.IOException;  
  
public class ExcelWriter {  
  
    public static void main(String[] args) {  
        // 创建一个新的工作簿对象  
        Workbook workbook = new XSSFWorkbook();  
        // 在工作簿中创建一个名为"Sheet1"的工作表  
        Sheet sheet = workbook.createSheet("Sheet1");  
  
        // 在工作表中创建第一行  
        Row row = sheet.createRow(0);  
        // 在第一行中创建第一个单元格,并设置其值为"Hello, World!"  
        Cell cell = row.createCell(0);  
        cell.setCellValue("Hello, World!");  
  
        try (FileOutputStream fos = new FileOutputStream("path/to/your/output/excel/file.xlsx")) {  
            // 将工作簿的内容写入输出流,即写入文件  
            workbook.write(fos);  
            // 刷新输出流,确保所有数据都写入文件  
            fos.flush();  
        } catch (IOException e) {  
            // 如果发生IO异常,打印堆栈跟踪  
            e.printStackTrace();  
        } finally {  
            try {  
                // 关闭工作簿,释放资源  
                workbook.close();  
            } catch (IOException e) {  
                // 如果关闭工作簿时发生异常,打印堆栈跟踪  
                e.printStackTrace();  
            }  
        }  
    }  
}

四 浏览器下载Excel示例(api示例):

java 复制代码
import org.apache.poi.xssf.usermodel.XSSFRow;  
import org.apache.poi.xssf.usermodel.XSSFSheet;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
import org.springframework.http.HttpStatus;  
import org.springframework.http.ResponseEntity;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RestController;  
  
import javax.servlet.http.HttpServletResponse;  
import java.io.IOException;  
import java.util.ArrayList;  
import java.util.List;  
  
@RestController  
public class StudentExcelController {  
  
    @GetMapping("/exportStudents")  
    public ResponseEntity<Void> exportStudents(HttpServletResponse response) throws IOException {  
        // 创建Excel文档  
        XSSFWorkbook workbook = new XSSFWorkbook();  
        XSSFSheet sheet = workbook.createSheet("学生信息");  
  
        // 创建表头  
        XSSFRow header = sheet.createRow(0);  
        header.createCell(0).setCellValue("姓名");  
        header.createCell(1).setCellValue("学号");  
        header.createCell(2).setCellValue("班级");  
        header.createCell(3).setCellValue("成绩");  
  
        // 填充数据  
        List<Student> students = getStudentList();  
        int rowIndex = 1;  
        for (Student student : students) {  
            XSSFRow row = sheet.createRow(rowIndex++);  
            row.createCell(0).setCellValue(student.getName());  
            row.createCell(1).setCellValue(student.getStudentId());  
            row.createCell(2).setCellValue(student.getClassName());  
            row.createCell(3).setCellValue(student.getScore());  
        }  
  
        // 设置响应头信息  
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");  
        response.setHeader("Content-Disposition", "attachment; filename=students.xlsx");  
  
        // 将Excel文档写入响应流中  
        workbook.write(response.getOutputStream());  
        workbook.close(); // 记得关闭workbook  
  
        return new ResponseEntity<>(HttpStatus.OK);  
    }  
  
    // 模拟获取学生数据  
    private List<Student> getStudentList() {  
        List<Student> students = new ArrayList<>();  
        students.add(new Student("张三", "20230001", "一班", 90));  
        students.add(new Student("李四", "20230002", "二班", 85));  
        students.add(new Student("王五", "20230003", "三班", 92));  
        return students;  
    }  
  
    // 学生实体类  
    static class Student {  
        private String name;  
        private String studentId;  
        private String className;  
        private double score;  
  
        public Student(String name, String studentId, String className, double score) {  
            this.name = name;  
            this.studentId = studentId;  
            this.className = className;  
            this.score = score;  
        }  
  
        public String getName() {  
            return name;  
        }  
  
        public String getStudentId() {  
            return studentId;  
        }  
  
        public String getClassName() {  
            return className;  
        }  
  
        public double getScore() {  
            return score;  
        }  
    }  
}
相关推荐
云游6 小时前
利用外部Postgresql及zookeeper,启动Apache Dolphinscheduler3.1.9
分布式·postgresql·zookeeper·apache·工作流任务调度
Aurora_NeAr1 天前
Apache Iceberg数据湖基础
apache
源图客1 天前
Apache Nutch介绍与部署编译
apache·nutch
FreeBuf_1 天前
Apache组件遭大规模攻击:Tomcat与Camel高危RCE漏洞引发数千次利用尝试
java·tomcat·apache
jingyu飞鸟1 天前
linux系统源代码安装apache、编译隐藏版本号
linux·运维·apache
vortex52 天前
Apache 配置文件提权的实战思考
apache
涤生大数据2 天前
Apache Spark 4.0:将大数据分析提升到新的水平
数据分析·spark·apache·数据开发
阿絮~3 天前
Apache RocketMQ进阶之路阅读笔记和疑问
笔记·apache·rocketmq
Fireworkitte5 天前
Apache POI 详解 - Java 操作 Excel/Word/PPT
java·apache·excel
蚂蚁数据AntData5 天前
从性能优化赛到社区Committer,走进赵宇捷在Apache Fory的成长之路
大数据·开源·apache·数据库架构