版权声明:本文为大都督作者的原创文章,未经 大都督 允许也可以转载,但请注明出处,谢谢! 共勉! https://blog.csdn.net/qq_37335220/article/details/84981576
将excel表格中数据导入MySQL数据库中
思路:创建模板 -> 下载模板 -> 填写内容 -> 导入数据(将导入失败的数据在页面中提示)
1. 创建excel模板(template.xlsx)
1.1 模板内容如图:
1.2.将该模板放到静态资源static下,New一个Folder(excel),如图:
2. 编写下载模板页面,填写数据后,导入
2.1 页面效果图:
2.2 填写数据
2.3 页面(import_excel_page.ftl)代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>poi技术</title>
<meta name="keywords" content="">
<meta name="description" content="">
<link rel="shortcut icon" href="favicon.ico">
<link href="../../css/bootstrap.min14ed.css?v=3.3.6" rel="stylesheet">
<link href="../../css/font-awesome.min93e3.css?v=4.4.0" rel="stylesheet">
<link href="../../css/plugins/iCheck/custom.css" rel="stylesheet">
<link href="../../css/style.min862f.css?v=4.1.0" rel="stylesheet">
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row">
<div class="col-sm-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>poi技术</h5>
</div>
<div class="ibox-content">
<div class="form-horizontal">
<div class="alert alert-warning">
1、点击右侧下载模板,从第2行开始录入数据。 <a class="alert-link" href="../../excel/template.xlsx">Excel模板下载</a><br/>
2、excel模板中有必填项为空时,将导入失败<br/>
</div>
<div id="file-pretty">
<div class="form-group">
<div class="col-sm-6">
<label class="font-noraml">选择要上传的excel文件</label>
<input type="file" class="form-control" id="excel_file_id" name="excel_file">
</div>
</div>
</div>
<div class="alert alert-danger" id="show_error_info_div" style="display:none;">
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4">
<button class="btn btn-primary" type="submit" onclick="import_template()">导入</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../../js/jquery.min.js?v=2.1.4"></script>
<script src="../../js/bootstrap.min.js?v=3.3.6"></script>
<script src="../../js/content.min.js?v=1.0.0"></script>
<script src="../../js/layer.js"></script>
<script src="../../js/plugins/prettyfile/bootstrap-prettyfile.js"></script>
<script src="../../js/ajaxfileupload.js"></script>
<script type="text/javascript">
$(function(){
$('input[type="file"]').prettyFile();
})
function import_template(){
$.ajaxFileUpload({
url:"/poi/batch_import",
secureuri:false,
fileElementId:'excel_file_id',
dataType: 'jsonp',
success: function (data, status){
$("#excel_file_id").val(null);
data = $.parseJSON(data.replace(/<.*?>/ig,""));
if(data.code=='0'){
layer.msg("导入成功", function() {
$("#show_error_info_div").attr("style","display:none");
window.location.reload();
})
}else if(data.code=='2'){
var ht =data.msg;
var strs= new Array(); //定义一数组
strs=ht.split("#"); //字符分割
var html_="";
for (i=0;i<strs.length ;i++ ){
html_+=strs[i]+'<br/>';
}
$("#show_error_info_div").html(html_);
$("#show_error_info_div").attr("style","");
}
},
error: function(data, status, e) {
alert("系统异常,请稍后再试!");
}
});
}
$("#excel_file_id").onclick(function(){
$("#excel_file_id").val(null);
})
</script>
</body>
</html>
2.4 引入poi依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.9</version>
</dependency>
2.5 编写Java代码
/**
*
* @Title: import_excel_page
* @Description: 跳转到import_excel_page页面
* @return
* @author 大都督
* @date 2018年12月12日
* @return String
*/
@RequestMapping("/import_excel_page")
public String import_excel_page() {
return "import_excel/import_excel_page";
}
/**
*
* @Title: batch_import_express
* @Description: 批量导入
* @param file
* @param request
* @return
* @throws Exception
* @author 大都督
* @date 2018年12月13日
* @return MessageInfo
*/
@RequestMapping(value = "/batch_import")
@ResponseBody
public MessageInfo batch_import_express(@RequestParam(value ="excel_file")MultipartFile file,HttpServletRequest request)throws Exception{
if(null == file){
return ResultInfo.tips("文件为空,请选择文件");
}
String fileName=file.getOriginalFilename();
if(!ExcelImportUtils.validateExcel(fileName)){
return ResultInfo.tips("文件必须是excel格式");
}
long size=file.getSize();
if(StringUtils.isEmpty(fileName) || size==0){
return ResultInfo.tips("文件不能为空");
}
String result_str = batchImport(fileName,file);
if(StringUtils.isEmpty(result_str)){
return ResultInfo.success();
}else{
String a ="其它正常数据已导入;异常数据信息请修改后重新导入。异常数据参照下方提示#";
return ResultInfo.tips(a+result_str);
}
}
public String batchImport(String fileName,MultipartFile mfile){
String pictures_url = "E:\\fileupload";
System.out.println(pictures_url);
File uploadDir = new File(pictures_url); //"E:\\fileupload"
//创建一个目录 (它的路径名由当前 File 对象指定,包括任一必须的父路径。)
if (!uploadDir.exists()) uploadDir.mkdirs();
//新建一个文件
File tempFile = new File(pictures_url + new Date().getTime() + ".xlsx");
//初始化输入流
InputStream is = null;
try{
//将上传的文件写入新建的文件中
mfile.transferTo(tempFile);
//根据新建的文件实例化输入流
is = new FileInputStream(tempFile);
//根据版本选择创建Workbook的方式
Workbook wb = null;
//根据文件名判断文件是2003版本还是2007版本
if(ExcelImportUtils.isExcel2007(fileName)){
wb = new XSSFWorkbook(is);
}else{
wb = new HSSFWorkbook(is);
}
//根据excel里面的内容读取知识库信息
return readExcelValue(wb,tempFile);
}catch(Exception e){
e.printStackTrace();
} finally{
if(is !=null)
{
try{
is.close();
}catch(IOException e){
is = null;
e.printStackTrace();
}
}
}
return "导入出错!请检查数据格式!";
}
private String readExcelValue(Workbook wb,File tempFile){
//错误信息接收器
String errorMsg = "";
//得到第一个shell
Sheet sheet=wb.getSheetAt(0);
//得到Excel的行数
int totalRows=sheet.getLastRowNum();
//总列数
int totalCells = 0;
//得到Excel的列数(前提是有行数),从第二行算起
if(totalRows>=1 && sheet.getRow(0) != null){
totalCells=sheet.getRow(0).getPhysicalNumberOfCells();
}
String br = "";
//循环Excel行数,从第二行开始。标题不入库
for(int r=1;r<=totalRows;r++){
String rowMessage = "";
Row row = sheet.getRow(r);
if (row == null){
errorMsg += br+"第"+(r+1)+"行数据有问题,请仔细检查!#";
continue;
}
String userName = "";
String age = "";
//循环Excel的列
for(int c = 0; c <totalCells; c++){
Cell cell = row.getCell(c);
if(c==0){
if(cell != null){
cell.setCellType(Cell.CELL_TYPE_STRING);
userName = cell.getStringCellValue();
if(StringUtils.isEmpty(userName)){
rowMessage += "姓名不能为空;";
break;
}
}else{
rowMessage += "第"+(c+1)+"列数据有问题,请仔细检查;";
break;
}
}
if (c == (totalCells-1)) {
if(cell != null){
cell.setCellType(Cell.CELL_TYPE_STRING);
age = cell.getStringCellValue();
if(StringUtils.isEmpty(age)){
rowMessage += "年龄不能为空";
break;
}
}else{
rowMessage += "第"+(c+1)+"列数据有问题,请仔细检查;";
break;
}
}
}
//拼接每行的错误提示
if(!StringUtils.isEmpty(rowMessage)){
errorMsg += br+"第"+(r+1)+"行,"+rowMessage+"#";
} else{
userDao.save(new User(userName, Integer.parseInt(age)));
}
}
//删除上传的临时文件
if(tempFile.exists()){
tempFile.delete();
}
return errorMsg;
}
3. 测试结果
3.1 页面效果图: