首先在maven项目中添加依赖
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>4.0.1</version> </dependency>保存到本地文件代码示例:
public void test() throws IOException { // 创建 excel 对象 XSSFWorkbook sheets = new XSSFWorkbook(); // 创建 excel 页(一个 excel 是可以有多个页的) XSSFSheet sheet = sheets.createSheet(); // 创建行,数字表示索引,从0开始,1表示第二行 XSSFRow row = sheet.createRow(1); // 在行中指定列,数字表示索引,从0开始,1表示第二列 XSSFCell cell = row.createCell(1); // 在列中写入数据 cell.setCellValue("hello excel!"); // 创建文件对象 File file = new File("test.xlsx"); // 创建写入到文件的流 FileOutputStream out = new FileOutputStream(file); // 将 excel 数据写入文件中 sheets.write(out); // 关闭 excel 流 sheets.close(); // 关闭文件流 out.close(); }web端下载代码示例:
public void test() throws IOException { XSSFWorkbook sheets = new XSSFWorkbook(); sheets.createSheet(); XSSFRow row = first.createRow(1); XSSFCell cell = row.createCell(1); cell.setCellValue("hello excel!"); // 解决文件名中文乱码 String fileName = new String("测试.xlsx".getBytes(), "iso-8859-1"); // 设置 content-type response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); // 设置 http 响应头 response.addHeader("content-disposition", "attachment;fileName=" + fileName); // 获取响应输出流 ServletOutputStream outputStream = response.getOutputStream(); // 将数据写入响应流 sheets.write(outputStream); outputStream.flush(); // 关闭流 sheets.close(); outputStream.close(); }