Poi介绍
常用于处理Excel数据 也可以处理word ,ppt可读可写。
Excel文件和poi中的组件对应关系
- 一个Excel文件对应于一个Workbook对象
- 一个Workbook可以有多个Sheet对象
- 一个Sheet对象由多个Row对象组成
- 一个Row对象是由多个Cell对象组成
对Excel的操作步骤
- 用Workbook打开或者创建一个Excel文件的对象
- 用上一步的Excel对象创建或者获取到一个Sheet对象
- 用Sheet对象创建或获取一个Row对象
- 用Row对象创建或获取一个Cell对象
- 对Cell对象读写
Poi的使用
添加maven依赖:
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
向Excel中写入数据:
// 创建一个Excel对象
XSSFWorkbook sheets = new XSSFWorkbook();
// 创建表单Sheet对象
XSSFSheet sheet = sheets.createSheet();
// 创建Row对象
XSSFRow row1 = sheet.createRow(0);
XSSFRow row2 = sheet.createRow(1);
XSSFRow row3 = sheet.createRow(2);
// 创建Cell对象,并进行写操作
// 第一行
XSSFCell cell = row1.createCell(0);
cell.setCellValue("姓名");
XSSFCell cell1 = row1.createCell(1);
cell1.setCellValue("年龄");
// 第二行
cell = row2.createCell(0);
cell.setCellValue("张三");
cell1 = row2.createCell(1);
cell1.setCellValue("22");
// 第二行
cell = row3.createCell(0);
cell.setCellValue("李四");
cell1 = row3.createCell(1);
cell1.setCellValue("20");
String excelName = "测 试.xlsx";
response.setContentType("application/octet-stream");
try {
ServletOutputStream outputStream = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment;filename=" + new String(excelName.getBytes("UTF-8"), "ISO8859-1"));
// IOUtils.copy()
sheets.write(outputStream);
response.flushBuffer();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
读取Excel中的数据:
public static List<List<Object>> readExcelData(InputStream inputStream){
List<List<Object>> allList = null;
try {
XSSFWorkbook sheets = new XSSFWorkbook(inputStream);
if(null == sheets){
return null;
}
//遍历Excel中所有的sheet
allList = new ArrayList<>();
for (Sheet sheet : sheets) {
//遍历当前sheet中的所有行
for (Row row: sheet) {
//遍历所有的列
List<Object> cellList = new ArrayList<>();
for (int c=row.getFirstCellNum();c<row.getLastCellNum();c++) {
Cell cell = row.getCell(c);
if (null != cell){
cellList.add(cell.getStringCellValue());
}else {
cellList.add("");
}
}
allList.add(cellList);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return allList;
}