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

embedded/2024/9/23 20:24:44/

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

一 引入依赖:
        <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示例:

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示例:

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示例):

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;  }  }  
}


http://www.ppmy.cn/embedded/7785.html

相关文章

【数据结构】顺序表:与时俱进的结构解析与创新应用

欢迎来到白刘的领域 Miracle_86.-CSDN博客 系列专栏 数据结构与算法 先赞后看&#xff0c;已成习惯 创作不易&#xff0c;多多支持&#xff01; 目录 一、数据结构的概念 二、顺序表&#xff08;Sequence List&#xff09; 2.1 线性表的概念以及结构 2.2 顺序表分类 …

计算机网络----第十三天

DNS协议和文件传输协议 DNS&#xff1a; 含义&#xff1a;用于域名和IP地址的互相解析 DNS域名&#xff1a; 背景&#xff1a;通过IP地址访问目标主机&#xff0c;不便于记忆 域名的树形层次化结构&#xff1a; ①根域 ②顶级域&#xff1a;主机所处的国家/区域&#xf…

【数据结构】霍夫曼树

1.概念 霍夫曼树&#xff08;Huffman Tree&#xff09;&#xff0c;又称最优二叉树&#xff0c;是一种带权路径长度最短的二叉树。在霍夫曼树中&#xff0c;叶子节点的权值通常代表字符出现的频率&#xff0c;非叶子节点的权值是其子节点权值的和。霍夫曼树广泛应用于数据压缩…

JenKins使用(Linux)

一、准备工作 1、Linux中装好JDK、Maven、Git这三个环境 &#xff08;1&#xff09;配置JDK的环境变量 &#xff08;2&#xff09;配置Maven的Setting.xml文件和环境变 &#xff08;3&#xff09;Git就不需要配置环境变量了 2、安装JenKins&#xff0c;注意网上说 JenKins…

纵行科技携ZETA传感器亮相深圳国际传感器与应用技术展览会

传感器是物联网时代的核心组成部分&#xff0c;在数字化转型和智能化趋势的推动下&#xff0c;全球传感器创新加速&#xff0c;市场持续增长&#xff0c;规模不断扩大。2024年4月14-16日&#xff0c;深圳国际传感器与应用技术展览会&#xff0c;在深圳会展中心&#xff08;福田…

不需要在 HTML 中添加任何额外的标签,就能实现复杂的设计效果。

1. 基础知识 什么是伪元素选择器 伪元素选择器用来指定一个元素的特定部分或者在元素中创建虚拟内容。 最常见的伪元素选择器包括 ::before 和 ::after&#xff0c;它们分别用于在元素内容的前面和后面添加内容或样式。 伪元素选择器是为了增强对元素的控制&#xff0c;它们…

Git的操作和使用

一、基本操作 1、创建git本地仓库 &#xff08;1&#xff09;创建目录&#xff1a;mkdir gitcode &#xff08;2&#xff09;进入目录&#xff1a;cd gitcode/ &#xff08;3&#xff09;查询目录内容&#xff1a;ls &#xff08;4&#xff09;在当前目录下创建git本地仓库…

MongoDB与MySQL的区别???MongoDB的优势???

MongoDB是一种开源的文档型数据库管理系统&#xff0c;它使用类似于JSON的BSON格式&#xff08;Binary JSON&#xff09;来存储数据。与传统关系型数据库不同&#xff0c;MongoDB不使用表和行的结构&#xff0c;而是采用集合&#xff08;Collection&#xff09;(Mysql表)和文档…