1.POI介绍
Apache POI是用Java编写的免费开源的跨平台的Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能,其中使用最多的就是使用POI操作Excel文件。
- POI结构:
HSSF - 提供读写Microsoft Excel XLS格式档案的功能
XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能
HWPF - 提供读写Microsoft Word DOC格式档案的功能
HSLF - 提供读写Microsoft PowerPoint格式档案的功能
HDGF - 提供读Microsoft Visio格式档案的功能
HPBF - 提供读Microsoft Publisher格式档案的功能
HSMF - 提供读Microsoft Outlook格式档案的功能
2. maven坐标
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
3.入门案例
3.1 从Excel文件读取数据
方式一:
通过获取工作表最后一个行号,从而根据行号获得行对象,通过行获取最后一个单元格索引,从而根据单元格索引获取每行的一个单元格对象
//创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook("/Users/.../Desktop/poiTest.xlsx");
//获取工作表,既可以根据工作表的顺序获取,也可以根据工作表的名称获取
XSSFSheet sheet = workbook.getSheetAt(0);
//获取当前工作表最后一行的行号,行号从0开始
int lastRowNum = sheet.getLastRowNum();
for(int i=0;i<=lastRowNum;i++){ // <= 🌟
//根据行号获取行对象 XSSFRow是Row的实现类
XSSFRow row = sheet.getRow(i);
short lastCellNum = row.getLastCellNum();//获取当前行最后一个单元格的索引
for(short j=0;j<lastCellNum;j++){ // < 🌟
//获取单元格对象
XSSFCell cell = row.getCell(j);
String value = cell.getStringCellValue();
System.out.println(value);
}
}
workbook.close();
方式二:
通过遍历工作表获得行,遍历行获得单元格,最终获取单元格中的值。
//创建工作簿 XSSFWorkbook代表一个excel文件
XSSFWorkbook excel = new XSSFWorkbook("/Users/.../Desktop/poiTest.xlsx");
//获取工作表,既可以根据工作表的顺序获取,也可以根据工作表的名称获取
XSSFSheet sheet = excel.getSheetAt(0);
//遍历工作表获得行对象
for (Row row : sheet) {
//遍历行对象获取单元格对象
for (Cell cell : row) {
//需判断类型...此处并未判断...
//获得单元格中的值
System.out.println(cell.getStringCellValue());
}
}
//关闭excel文件
excel.close();
3.2 向Excel文件写入数据
使用POI可以在内存中创建一个Excel文件并将数据写入到这个文件,最后通过输出流将内存中的Excel文件保存到磁盘
//创建excel(在内存中创建)
XSSFWorkbook excel = new XSSFWorkbook();
//创建工作表 ,指定工作表名称 (在内存中创建 默认没有工作表,所以需创建工作表)
XSSFSheet sheet = excel.createSheet("sheet表1");
//创建行,0表示第一行
XSSFRow title = sheet.createRow(0);
//创建单元格并赋值,0表示第一个单元格
title.createCell(0).setCellValue("编号");
title.createCell(1).setCellValue("姓名");
title.createCell(2).setCellValue("年龄");
XSSFRow row1 = sheet.createRow(1);
row1.createCell(0).setCellValue("1");
row1.createCell(1).setCellValue("小明");
row1.createCell(2).setCellValue("10");
XSSFRow row2 = sheet.createRow(2);
row2.createCell(0).setCellValue("2");
row2.createCell(1).setCellValue("小王");
row2.createCell(2).setCellValue("20");
//通过输出流将excel对象下载到磁盘
FileOutputStream out = new FileOutputStream("/Users/.../Desktop/poiTest2.xlsx");
excel.write(out);//输出流传进去
out.flush();//刷新文件
out.close();
excel.close();
4. 封装为工具类
public class POIUtils {
private final static String xls = "xls";
private final static String xlsx = "xlsx";
private final static String DATE_FORMAT = "yyyy/MM/dd";
/**
* 读入excel文件,解析后返回
* @param file
* @throws IOException
*/
public static List<String[]> readExcel(MultipartFile file) throws IOException {
// 1.检查文件的合法性
checkFile(file);
// 2.获得Workbook工作薄对象
Workbook workbook = getWorkBook(file);
// 3.创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
List<String[]> list = new ArrayList<String[]>();// list中装解析到的数据
if(workbook != null){
//遍历sheet工作表
for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
//获得当前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if(sheet == null){
continue;
}
//获得当前sheet的开始行
int firstRowNum = sheet.getFirstRowNum();
//获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
//循环除了第一行的所有行 标题不需要解析
for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
//获得当前行
Row row = sheet.getRow(rowNum);
if(row == null){
continue;
}
//获得当前行的开始列
int firstCellNum = row.getFirstCellNum();
/*
getPhysicalNumberOfCells():获取不为空的的列个数;
getLastCellNum():获取最后一个不为空的列是第几个。
*/
//获得当前行的列个数 获取不为空的的列个数。
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
//循环当前行
for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
Cell cell = row.getCell(cellNum);
// 将单元格数据 统一转为String类型来...
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
workbook.close();
}
return list;
}
// 1.校验文件是否合法
public static void checkFile(MultipartFile file) throws IOException{
//1判断文件是否存在
if(null == file){
throw new FileNotFoundException("文件不存在!");
}
//2判断文件是否是excel文件
//2.1获得文件名
String fileName = file.getOriginalFilename();
//2.2
if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
throw new IOException(fileName + "不是excel文件");
}
}
// 2.获得Workbook工作薄对象
public static Workbook getWorkBook(MultipartFile file) {
//获得文件名
String fileName = file.getOriginalFilename();
//创建Workbook工作薄对象,表示整个excel
Workbook workbook = null;
try {
//获取excel文件的io流
InputStream is = file.getInputStream();
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象 🌟
if(fileName.endsWith(xls)){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith(xlsx)){
//2007
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
public static String getCellValue(Cell cell){
String cellValue = "";
if(cell == null){
return cellValue;
}
//判断当前单元格内容类型
String dataFormatString = cell.getCellStyle().getDataFormatString();
//如果当前单元格内容为日期类型,需要特殊处理
if(dataFormatString.equals("m/d/yy")){
cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());
return cellValue;
}
//把数字当成String来读,避免出现1读成1.0的情况
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//判断数据的类型
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC: //数字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
}