如何使用POI技术
什么是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格式档案的功能 -
使用:
-
导包
<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>
-
常用方法
- 读入文件
- XSSFWorkbook,读入xlsx,把excel内存读入内存,并组织结构树(占内存,支持公式的计算)
- SXSSFWorkbook,读入xlsx,以解析xml的方式来加载excel(不是很占内存,不支持公式的计算)
- HSSFWorkbook,读入xls
- 获取sheet页,getSheetAt()
- 获取数据大小
- sheet.getLastRowNum(),获取当前sheet页中有多少行数据,从1开始
- sheet.getFirstRowNum(),获取当前sheet页中第一行数据开始的行号
- row.getLastCellNum(),获取行有多少个单元格,从0开始
- row.getPhysicalNumberOfCells,获取最大的单元格下标
- 读入文件
-
兼容上传文件的格式校验
//上传之前进行文件格式校验
beforeUpload(file){
if(file.type==""){
let name = file.name
console.log((name.endsWith('.xls')||name.endsWith('.xlsx')))
}else{
const isXLS = file.type === 'application/vnd.ms-excel';
if(isXLS){
return true;
}
const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
if (isXLSX) {
return true;
}
this.$message.error('上传文件只能是xls或者xlsx格式!');
return false;
}
},