excel表格文件怎么解析?别慌,Apache早已有解决方式。以下,从应用的角度实现Excel文件上传并解析
语言:Java、Vue
1.文件转base64格式传输
<el-upload
class="action-btn"
:multiple="false"
:show-file-list="false"
:with-credentials="true"
accept=".xlsx,.xls"
name="file"
:headers="headers"
:http-request="uploadFileByBase64"
>
<el-button >上传</el-button>
</el-upload>
<!-- headers根据条件添加,action -->
// 以base64格式进行文件上传
uploadFileByBase64(file, fileList) {
this.getBase64(file.file).then(async (res) => {
const fileBase64 = res;
const param = {
fileName: file.file.name,
fileStr: fileBase64, // 需要带上格式前缀
};
await api.uploadFile({
param,
}).then((v) => {
this.$message.success('文件上传成功!');
console.log('上传结果 v = ', v);
}).catch((err) => {
this.$message.warning('文件上传异常,请检查文件格式!');
});
});
},
// 文件转base64-- 摘抄自网络……
getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
let fileResult = '';
reader.readAsDataURL(file);
// 开始转
reader.onload = function () {
fileResult = reader.result;
};
// 转失败
reader.onerror = function (error) {
reject(error);
};
// 成功
reader.onloadend = function () {
resolve(fileResult);
};
});
},
为什么要使用base64字符串?
2.解析
2.1 base64 -> MultipartFile
public static MultipartFile base64ToMultipart(String fileStr) {
try {
String[] baseStr = fileStr.split(",");
if(baseStr.length != 2) {
log.error("base64ToMultipartToStream 输入base64字符串无文件前缀, fileStr = {}", fileStr);
return null;
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = new byte[0];
b = decoder.decodeBuffer(baseStr[1]);
for(int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64DecodedMultipartFile(b, baseStr[0]);
} catch (IOException e) {
log.error("error")
}
}
/**
* 文件base64字符串 -> MultipartFile -> 字节数入流
* (此处 fileStr 需要添加文件格式化后的前缀,例如 .xlsx base64字符的前缀:'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' )
*/
2.2 内容校验,实例化
使用apache提供工具包, 详情:https://mvnrepository.com/artifact/org.apache.poi
<!--excel-xls-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
<!--excel-xlsx-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.6</version>
</dependency>
private List<BeanParam> readAndConstruct(InputStream file) {
List<BeanParam> resultList = new ArrayList<>(); // 目标实体
DecimalFormat decimalFormat = new DecimalFormat("0"); // 格式化数字
try {
// 当文件类型为.xls 使用HSSF
//HSSFWorkbook xwb = new HSSFWorkbook(new POIFSFileSystem(file));
//HSSFSheet sheet = xwb.getSheetAt(0);
//HSSFRow row = null;
//HSSFCell cell = null;
// 当文件类型为.xlsx,使用XSSF
OPCPackage pkg = OPCPackage.open(file);
XSSFWorkbook xwb = new XSSFWorkbook(pkg);
XSSFSheet sheet = xwb.getSheetAt(0);
XSSFRow row = null; // 一行
XSSFCell cell = null; // 一单元
for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getPhysicalNumberOfRows(); i++) {
BeanParam vo = new BeanParam();
row = sheet.getRow(i);
if (row == null) {
continue;
}
String categoryStr = "";
cell = row.getCell(0); // 得到第一行第一个单元格
if(cell == null){
continue;
}
switch(cell.getCellType()){ // 类型
case HSSFCell.CELL_TYPE_STRING:
categoryStr = cell.getStringCellValue().trim();break;
case HSSFCell.CELL_TYPE_NUMERIC:
categoryStr = decimalFormat.format(cell.getNumericCellValue());break;
default:
categoryStr = cell.getStringCellValue().trim();break;
}
vo.setCateId(Long.parseLong(categoryStr));
.
.
.
.
.
cell = row.getCell(5);
if(cell == null){
continue;
}
vo.setName(getValByCell(cell));
.
.
.
resultList.add(vo);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
/**
*通过这种方式,可对excel格式内容进行校验,同时将其实例化为目标对像
*
**/