<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
public Boolean upLoadPowerData(MultipartFile multipartFile) {
File file = null;
InputStream inputStream = null;
HSSFWorkbook workbook = null;
HSSFSheet sheet = null;
int sheetRowCount = 0;
String sheetName = null;
try {
file = ExcelUtils.fileTransformation(multipartFile);
if (file == null) {
return false;
}
inputStream = new FileInputStream(file.getAbsolutePath());
workbook = new HSSFWorkbook(inputStream);
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
// 对于sheet中的数据处理
// 获取当前sheet
sheet = workbook.getSheetAt(i);
// 获取sheet总行数
sheetRowCount = sheet.getPhysicalNumberOfRows();
// 获取sheet名称
sheetName = sheet.getSheetName();
// 获取当前sheet第一行、第一列数据
sheet.getRow(0).getCell(0);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public class ExcelUtils {
//文件转换MultipartFile ->File
public static File fileTransformation(MultipartFile file) throws IOException {
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
return toFile;
}
return toFile;
}
public static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@ApiOperation("上传excel数据文件")
@PostMapping("/upload")
public R uploadExcel(@RequestParam MultipartFile file) throws IOException {
return new R<>(demoService.upLoadPowerData(file));
}
使用了element-ui的上传组件,详细配置可以去看下element-ui的文档
<el-upload
class="upload-demo uploadData"
style="text-align: right;margin-left: 10px"
action="https://jsonplaceholder.typicode.com/posts/"
accept=".xls,.xlsx"
:before-upload="importExcel"
:limit="1">
<el-button slot="trigger" ref="file" size="small" class="addBtn"
style="background-color: #f9a038;color:white;">数据导入
</el-button>
</el-upload>
axios请求封装
import request from '@/router/axios'
// 导入excel
export function uploadExcel(data) {
return request({
url: '/demo/upload',
method: 'post',
data: data
})
}
js导入方法
importExcel(file) {
this.loading = true;
const data = new FormData();
data.append('file', file);
uploadExcel(data).then(res => {
if (res.data.data) {
this.$message({
message: "导入成功!",
type: "success"
});
} else {
this.$message({
message: "导入失败,请校验数据!",
type: "warning"
});
}
this.loading = false;
})
}
@ApiOperation("下载excel数据文件")
@GetMapping("/download/{demoId}")
public void downLoadExcel(@PathVariable Integer demoId, HttpServletResponse response) throws IOException {
// 获取workbook对象
HSSFWorkbook workbook = demoService.downLoadPowerData(demoId, year);
response.setCharacterEncoding("utf-8");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("demo.xls", "UTF-8"));
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
workbook.write(response.getOutputStream());
}
封装axios请求
import request from '@/router/axios'
// 下载excel
export function downLoadExcel(demoId) {
return request({
url: '/demo/download/' + demoId ,
method: 'get',
responseType: 'blob'
})
}
js方法处理
exportExcel() {
this.loading = true;
downLoadExcel(parseInt(this.demoId)).then(response => {
const link = document.createElement('a');
let blob = new Blob([response.data], {type: 'application/vnd.ms-excel;charset=UTF-8'});
link.style.display = 'none';
link.href = URL.createObjectURL(blob);
link.download = "demo.xls";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
this.loading = false;
});
}