文章目录
一、POI 地基 - 依赖
<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>
<!-- POl 报表导出对象 所需依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
二、创建 POI 报表的相关操作
创建 POI 报表主要有四大块,即 Excel 文件、工作空间、行、单元格
行、列 均从 0 开始
2-1】创建有内容的 Excel 表格 .xlsx
package com.debj.day2020620_poi_lx.poi;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class POIDemo {
public static void main(String[] args) throws IOException {
/**
* 基本 Excel 表格 .xlsx 创建
*/
// 创建工作库
XSSFWorkbook wb = new XSSFWorkbook();
// 创建 Sheet
XSSFSheet sheet = wb.createSheet("工作区间 01");
// 创建行对象,从 0 开始
XSSFRow row = sheet.createRow(3);
// 创建单元格,从 0 开始
XSSFCell cell = row.createCell(0);
// 单元格写入数据
cell.setCellValue("debj");
/**
* 创建流,写出文件至 d 盘下 a.xlsx
*/
FileOutputStream fos = new FileOutputStream("D://a.xlsx");
wb.write(fos);
fos.close();;
}
}
2-2】给单元格增添样式
package com.debj.day2020620_poi_lx.poi;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
public class POIDemo {
public static void main(String[] args) throws IOException {
/**
* 基本 Excel 表格 .xlsx 创建
*/
// 创建工作库
XSSFWorkbook wb = new XSSFWorkbook();
// 创建 Sheet
XSSFSheet sheet = wb.createSheet("工作区间 01");
// 创建行对象,从 0 开始
XSSFRow row = sheet.createRow(3);
// 创建单元格,从 0 开始
XSSFCell cell = row.createCell(0);
// 单元格写入数据
cell.setCellValue("debj");
/**
* 单元格内容 的 样式
*/
XSSFCellStyle cellStyle = wb.createCellStyle();
// 设置边框
cellStyle.setBorderBottom(BorderStyle.DASH_DOT); // 下边框
cellStyle.setBorderTop(BorderStyle.HAIR); // 上边框
// 设置字体
Font font = wb.createFont(); // 创建字体对象
font.setFontName("楷体"); // 设置字体
font.setFontHeightInPoints((short)28); // 设置字号
cellStyle.setFont(font);
// 设置宽高
sheet.setColumnWidth(0,31*256); // 设置第一列的宽度是 31 个字符宽度
row.setHeightInPoints(50); // 设置行的高度是 50 个点
// 设置居中
cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
// 应用单元格样式
cell.setCellStyle(cellStyle);
/**
* 创建流,写出文件至 d 盘下 a.xlsx
*/
FileOutputStream fos = new FileOutputStream("D://a.xlsx");
wb.write(fos);
fos.close();;
}
}
2-3】再加入图片
package com.debj.day2020620_poi_lx.poi;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class POIDemo {
public static void main(String[] args) throws IOException {
/**
* 基本 Excel 表格 .xlsx 创建
*/
// 创建工作库
XSSFWorkbook wb = new XSSFWorkbook();
// 创建 Sheet
XSSFSheet sheet = wb.createSheet("工作区间 01");
// 创建行对象,从 0 开始
XSSFRow row = sheet.createRow(3);
// 创建单元格,从 0 开始
XSSFCell cell = row.createCell(0);
// 单元格写入数据
cell.setCellValue("debj");
/**
* 单元格内容 的 样式
*/
XSSFCellStyle cellStyle = wb.createCellStyle();
// 设置边框
cellStyle.setBorderBottom(BorderStyle.DASH_DOT); // 下边框
cellStyle.setBorderTop(BorderStyle.HAIR); // 上边框
// 设置字体
Font font = wb.createFont(); // 创建字体对象
font.setFontName("楷体"); // 设置字体
font.setFontHeightInPoints((short)28); // 设置字号
cellStyle.setFont(font);
// 设置宽高
sheet.setColumnWidth(0,31*256); // 设置第一列的宽度是 31 个字符宽度
row.setHeightInPoints(50); // 设置行的高度是 50 个点
// 设置居中
cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
// 应用单元格样式
cell.setCellStyle(cellStyle);
/**
* 图片操作
*/
// 读取图片流
FileInputStream fis = new FileInputStream("D:\\debj\\picture\\头像\\a.jpg");
// 读取图片到二进制数组
byte[] bytes = IOUtils.toByteArray(fis);
fis.read(bytes);
// 向 Excel 添加一张图片,并返回该图片在 Excel 中的图片集合中的下标
int i = wb.addPicture(bytes, XSSFWorkbook.PICTURE_TYPE_JPEG);
// 绘图工具
XSSFCreationHelper helper = wb.getCreationHelper();
Drawing<?> patriarch = sheet.createDrawingPatriarch();
// 创建锚点,设置图片坐标
ClientAnchor anchor = helper.createClientAnchor();
anchor.setRow1(4); // 第 五 行
anchor.setCol1(1); // 第 B 列
// 创建图片
Picture picture = patriarch.createPicture(anchor, i);
picture.resize();
/**
* 创建流,写出文件至 d 盘下 a.xlsx
*/
FileOutputStream fos = new FileOutputStream("D://a.xlsx");
wb.write(fos);
fos.close();;
}
}
三、读取 Excel 表格
package com.debj.day2020620_poi_lx.poi;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
public class ReadDemo {
public static void main(String[] args) throws IOException {
XSSFWorkbook wb = new XSSFWorkbook("D:\\read.xlsx"); // 这是要读取的 Excel
XSSFSheet sheet = wb.getSheetAt(0); // 获取 Sheet ( 第一个工作空间 )
// 获取 Sheete 中的每一行,和每个单元格
for(int rowNum = 0;rowNum <= sheet.getLastRowNum(); rowNum++){
XSSFRow row = sheet.getRow(rowNum); // 通过索引获取每一行
StringBuilder sb = new StringBuilder();
// 附注:cellNum 是从第 i+1 列开始读( 从 0 开始 )
for(int cellNum = 0;cellNum < row.getLastCellNum(); cellNum++){
XSSFCell cell = row.getCell(cellNum); // 通过 索引获取每个单元格
if (null==cell){
continue;
}
Object value = getCellValue(cell); // 获取单元格内容
sb.append(value+" \t");
}
System.out.println(sb.toString());
}
}
/**
* 判断内容格式,根据格式获取内容
* @param cell
* @return
*/
public static Object getCellValue(Cell cell){
CellType cellType = cell.getCellType(); // 获取到单元格的数据类型
Object value = null;
switch (cellType){
case STRING:
value = cell.getStringCellValue();
break;
case BOOLEAN:
value = cell.getBooleanCellValue();
break;
case NUMERIC:
if(DateUtil.isCellDateFormatted(cell)){
value = cell.getDateCellValue(); // 日期格式
} else {
value = cell.getNumericCellValue(); // 数字
}
break;
case FORMULA:
value = cell.getCellFormula(); // 公式类型
break;
default:
break;
}
return value;
}
}
四、实例 - 报表导出对象
1/3 实体类
package com.debj.entity;
public class User {
private Integer id;
private String name;
private String sex;
private String date; // 建议时间为 String 格式
// 还需生成 get/set,全参、无参 构造
}
2/3 工具类
package com.debj.day2020620_poi_lx.util;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class DownloadUtils {
public void download(
ByteArrayOutputStream byteArrayOutputStream,
HttpServletResponse response,
String returnName)
throws IOException {
response.setContentType("application/octet-stream");
//保存的文件名,必须和页面编码一致,否则乱码
returnName = response.encodeURL(new String(returnName.getBytes(),"ISO-8859-1"));
response.addHeader("Content-Disposition","attachment;filename="+returnName);
response.setContentLength(byteArrayOutputStream.size());
response.addHeader("Content-Length", "" + byteArrayOutputStream.size());
ServletOutputStream outputstream = response.getOutputStream(); //取得输出流
byteArrayOutputStream.writeTo(outputstream); //写到输出流
byteArrayOutputStream.close(); // 关闭
outputstream.flush(); // 刷新数据
}
}
3/3 controller 层
package com.debj.day2020620_poi_lx.controller;
import com.debj.day2020620_poi_lx.entity.User;
import com.debj.day2020620_poi_lx.util.DownloadUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Controller
public class UserController {
@RequestMapping(value = "/getPOI")
public void getPOIFromUser(
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
List<User> list = new ArrayList<>();
User u1 = new User(1,"蜘蛛侠","男","200200620");
User u2 = new User(2,"钢铁侠","男","200200620");
User u3 = new User(3,"美队","男","200200620");
User u4 = new User(4,"雷神","男","200200620");
User u5 = new User(5,"蚁人","男","200200620");
list.add(u1);
list.add(u2);
list.add(u3);
list.add(u4);
list.add(u5);
// 创建工作簿
Workbook wb = new XSSFWorkbook();
// 构造 sheet
Sheet sheet = wb.createSheet();
// 创建行
String[] titles = "编号,姓名,性别,日期".split(",");
Row row = sheet.createRow(0);
int titleIndex = 0;
for(String title:titles)
{
Cell cell = row.createCell(titleIndex++);
cell.setCellValue(title);
}
int rowIndex = 1;
//4.创建单元格
for(User u:list)
{
row = sheet.createRow(rowIndex++);
Cell cell = row.createCell(0);
cell.setCellValue(u.getId());
cell = row.createCell(1);
cell.setCellValue(u.getName());
cell = row.createCell(2);
cell.setCellValue(u.getSex());
cell = row.createCell(3);
cell.setCellValue(u.getDate());
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
wb.write(os);
// 导出
new DownloadUtils().download(os,response,"复仇者联盟.xlsx");
}
}
>>> 本地测试连接 <<<
五、部分示例截图
- 创建 a.xlsx 完整截图
- 读取 Excle 截图
- 网络下载 Excel 截图