好久沒寫了,寫一下最近用到的導(dǎo)入excel文件的功能吧
1敲霍、maven的pom文件添加依賴
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>RELEASE</version>
</dependency>
2俊马、excel導(dǎo)入工具類
public static List<Object[]> importExcel(InputStream inputStream) {
try {
List<Object[]> list = new ArrayList<>();
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
//獲取sheet的行數(shù)
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < rows; i++) {
//過濾表頭行
if (i == 0) {
continue;
}
//獲取當(dāng)前行的數(shù)據(jù)
Row row = sheet.getRow(i);
Object[] objects = new Object[row.getPhysicalNumberOfCells()];
int index = 0;
for (Cell cell : row) {
if (cell.getCellType().equals(NUMERIC)) {
objects[index] = numberFormat.format(cell.getNumericCellValue());
}
if (cell.getCellType().equals(STRING)) {
objects[index] = cell.getStringCellValue();
}
if (cell.getCellType().equals(BOOLEAN)) {
objects[index] = cell.getBooleanCellValue();
}
if (cell.getCellType().equals(ERROR)) {
objects[index] = cell.getErrorCellValue();
}
index++;
}
list.add(objects);
}
log.info("導(dǎo)入文件解析成功!");
return list;
}catch (Exception e){
log.info("導(dǎo)入文件解析失敿玷尽柴我!");
e.printStackTrace();
}
return null;
}
3、前端導(dǎo)入按鈕(本人使用的是layui)
layui.use(['form', 'layedit','upload', 'excel','laydate'], function () {
upload.render({
elem: '#uploadFile' //緇戝畾鍏冪礌
,accept:'file'
,exts:'xls|xlsx'
,url: '/board/upload' //涓婁紶鎺ュ彛
,type: 'post'
,done: function(res){
layerTips.msg(res.msg);
apply.table.bootstrapTable('refresh', apply.queryParams());
}
,error: function(){
//璇鋒眰寮傚父鍥炶皟
layerTips.msg("上傳失敗");
}
});
});
4扩然、后臺處理
public Map upload(@RequestParam("file") MultipartFile file) {
return baseBiz.upload(file);
}
public Map upload(MultipartFile file){
Map resultMap = new HashMap();
if (file != null) {
saveFile(resultMap,file);
if (resultMap.get("code").equals("0")) {
Map fileMap = new HashMap();
fileMap.put("src", "");
resultMap.put("data", fileMap);
return resultMap;
} else {
return resultMap;
}
}
return resultMap;
}
public void saveFile( Map<String,Object> resultMap,MultipartFile file) {
if (file.isEmpty()) {
return;
}
try {
List<Object[]> objects = ExcelUtil.importExcel(file.getInputStream());
for (Object[] os : objects) {
MessageBoard entity=MessageBoard.builder().id(Long.parseLong(String.valueOf(os[0]))).telphone(String.valueOf(os[1])).message(String.valueOf(os[2])).build();
if(selectById(entity.getId())==null){
insertSelective(entity);
}else{
updateSelectiveById(entity);
}
}
resultMap.put("filename", file.getOriginalFilename());
resultMap.put("saveUrl", "");
resultMap.put("code", "0");
resultMap.put("msg", "導(dǎo)入成功艘儒!");
return ;
} catch (Exception e) {
e.printStackTrace();
resultMap.put("code", "-2");
resultMap.put("msg", "導(dǎo)入異常!");
return ;
}
}
至此導(dǎo)入工作已經(jīng)完成夫偶,到數(shù)據(jù)庫核對數(shù)據(jù)是否導(dǎo)入正常即可