将本地Excel导入到数据库中
1. POM添加坐标
<!--poi(导入导出excel)-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
- html添加导入页面
<div class="panel panel-default">
<div class="panel-heading">
Excel数据导入到数据库小工具(必须是指定excel模板)
</div>
<div class="panel-body">
<form action="/common/import" method="post" class="form-inline" enctype="multipart/form-data">
<input type="file" class="form-control" name="file">
<input type="submit" value="导入" class="btn btn-default form-control"/>
</form>
</div>
<br><br>
<div class="panel-footer">
<img src="../img/excel_model.png">
<img src="../img/excel_model2.png">
</div>
</div>
- 点击导入按钮到,进入controller
/**
* 接受文件 解析 上传资料。
* @param file
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping("import")
public String importExcel(@RequestParam("file") MultipartFile file, HttpServletResponse response,
HttpServletRequest request)throws Exception {
if(!file.isEmpty()){
//把文件名子换成(时间搓.png)
String fileName=DateUtil.formatDate(new Date(), "yyyyMMdd-HHmmssSSS")+"_"+file.getOriginalFilename();
FileUtil.makeDirs(import_path);
//保存服务器
file.transferTo(new File(import_path+fileName));
//保存服务器
//解析
List<PMain> list = excel_to_clientInfo(new File(import_path+fileName));
//解析
//开始 上传 数据库
for(PMain pMain:list) {
pMainService.saveMain(pMain);
}
//开始 上传 数据库
//删除用过的文件
FileUtil.deleteFile(import_path+fileName);
//删除用过的文件
}
return "导入成功!!!<br/><a href='/main/findAll'>返回<a>";
}
/**
* 文件导入时调用
* @param userUploadFile
* @return
*/
private List<PMain> excel_to_clientInfo(File userUploadFile) {
List<PMain> list = new ArrayList<PMain>();
PMain pMain = null;
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(userUploadFile));
HSSFWorkbook wb = new HSSFWorkbook(fs);
//获取第一个sheet页
HSSFSheet sheet = wb.getSheetAt(0);
if(sheet!=null){
for(int rowNum =1;rowNum<=sheet.getLastRowNum();rowNum++){
HSSFRow row = sheet.getRow(rowNum);
if(row==null){
continue;
}
pMain =new PMain();
//去掉编码中的 .0 如果全是数字 后面有.0
pMain.setPhone(ExcelUtil.formatCell(row.getCell(1)));
pMain.setName(ExcelUtil.formatCell(row.getCell(2)));
pMain.setPosition1(ExcelUtil.formatCell(row.getCell(3)));
pMain.setPosition2(ExcelUtil.formatCell(row.getCell(4)));
//如果应用账号是数值型的,就会带有.0,为防止此类情况发生,直接将.0去除
String temp = ExcelUtil.formatCell(row.getCell(5));
temp = temp.replaceAll("[.]0$", "");
pMain.setAccount(temp);
//数值类型(由于表中有时写字符,有时写数值)
String change_countStr = ExcelUtil.formatCell(row.getCell(6)).trim();
if (change_countStr.equals("")) {
pMain.setChange_count(null);
} else {
change_countStr = change_countStr.replaceAll("[.]0$", "");
pMain.setChange_count(Integer.parseInt(change_countStr));
}
String update_count = ExcelUtil.formatCell(row.getCell(6)).trim();
if (update_count.equals("")) {
pMain.setUpdate_count(null);
} else {
update_count = update_count.replaceAll("[.]0$", "");
pMain.setUpdate_count(Integer.parseInt(update_count));
}
pMain.setStart_time(row.getCell(8).getDateCellValue());
pMain.setEnd_time(convertDateString(ExcelUtil.formatCell(row.getCell(9))));
pMain.setChange_time(convertDateString(ExcelUtil.formatCell(row.getCell(10))));
pMain.setExplain(ExcelUtil.formatCell(row.getCell(11)));
pMain.setImei(ExcelUtil.formatCell(row.getCell(12)));
/*状态采用颜色区分*/
short color = row.getCell(1).getCellStyle().getFillForegroundColor();
short color2 = row.getCell(1).getCellStyle().getFillPattern();
if (color == 64 || color == 9) {
pMain.setStatus("1");
} else if (color == 40) {
pMain.setStatus("0");
} else if (color == 64) {
pMain.setStatus("1");
} else if (color == 13) {
pMain.setStatus("2");
} else if (color == 17) {
pMain.setStatus("3");
}
list.add(pMain);
}
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return list;
}
- ExcelUtils.java
package com.sierte.phone.util;
import org.apache.poi.hssf.usermodel.HSSFCell;
public class ExcelUtil {
/**
* 格式化单元格返回其内容 格式化成string返回。
*
* @param cell
* @return
*/
public static String formatCell(HSSFCell cell) {
if (cell == null) {
return "";
} else {
if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
} else {
return String.valueOf(cell.getStringCellValue());
}
}
}
}
- FileUtil.java
package com.sierte.phone.util;
import java.io.File;
public class FileUtil {
/**
* 创建一个文件夹
* 如果存在 不创建
* 如果不存在 创建
* @param filePath
* @return
*/
public static boolean makeDirs(String filePath) {
File folder = new File(filePath);
return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
}
/**
* 删除单个文件
* 路径 是全路径
* c盘啥啥的全路径
* @param fileName 要删除的文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
return true;
} else {
//System.out.println("删除单个文件" + fileName + "失败!");
return false;
}
} else {
//System.out.println("删除单个文件失败:" + fileName + "不存在!");
return false;
}
}
}