Java导入excel并保存到数据库
首先建立好excel表格,并对应excel表格创建数据库表。
前台jsp页面:其中包含js
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>导入excel</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="导入excel">
<script type="text/javascript" src="view/js/jquery-1.8.2.js"></script>
</head>
<script type="text/javascript">
var User = function() {
this.init = function() {
//模拟上传excel
$("#uploadEventBtn").unbind("click").bind("click", function() {
$("#uploadEventFile").click();
});
$("#uploadEventFile").bind("change", function() {
$("#uploadEventPath").attr("value", $("#uploadEventFile").val());
});
};
//点击上传钮
this.uploadBtn = function() {
var uploadEventFile = $("#uploadEventFile").val();
if (uploadEventFile == '') {
alert("请择excel,再上传");
} else if (uploadEventFile.lastIndexOf(".xls") < 0) {//可判断以.xls和.xlsx结尾的excel
alert("只能上传Excel文件");
} else {
var url = "excel/import.do";
var formData = new FormData($('form')[0]);
user.sendAjaxRequest(url, "POST", formData);
}
};
this.sendAjaxRequest = function(url, type, data) {
$.ajax({
url : url,
type : type,
data : data,
dataType : "json",
success : function(result) {
alert(result.message);
},
error : function(result) {
alert(result.message);
},
cache : false,
contentType : false,
processData : false
});
};
};
var user;
$(function() {
user = new User();
user.init();
});
</script>
<body>
<form enctype="multipart/form-data" id="batchUpload" action="/excel/import" method="post" class="form-horizontal">
<button class="btn btn-success btn-xs" id="uploadEventBtn" style="height:26px;" type="button" >择文件</button>
<input type="file" name="file" style="width:0px;height:0px;" id="uploadEventFile">
<input id="uploadEventPath" disabled="disabled" type="text" placeholder="请择excel表" style="border: 1px solid #e6e6e6; height: 26px;width: 200px;" />
</form>
<button type="button" class="btn btn-success btn-sm" onclick="user.uploadBtn()" >上传</button>
</body>
</html>
后台代码:
Controller
import java.util.HashMap;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import service.ImportService; @Controller
@RequestMapping("/excel")
public class ImportExcelController{
@Autowired(required=true)
private ImportService importService; //导入excel
@RequestMapping(value = "/import", method=RequestMethod.POST)
@ResponseBody
public Map<String, Object> importExcel(@RequestParam(value="file",required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response){
Map<String, Object> map = new HashMap<String, Object>();
String result = importService.readExcelFile(file);
map.put("message", result);
return map;
} }
service:
import org.springframework.web.multipart.MultipartFile; public interface ImportService { /**
* 读取excel中的数据,生成list
*/
String readExcelFile(MultipartFile file); }
serviceImpl:
import java.util.List;
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile; import service.ImportService;
import controller.ReadExcel;
import dao.UserDao; @Service
public class ImportServiceImpl implements ImportService {
@Autowired(required = true)
private UserDao userDao;
@Override
public String readExcelFile(MultipartFile file) {
String result = "";
//创建处理EXCEL的类
ReadExcel readExcel = new ReadExcel();
//解析excel,获取上传的事件单
List<Map<String, Object>> userList = readExcel.getExcelInfo(file);
//至此已经将excel中的数据转换到list里面了,接下来就可以操作list,可以进行保存到数据库,或者其他操作,
for(Map<String, Object> user:userList){
int ret = userDao.insertUser(user.get("name").toString(), user.get("sex").toString(), Integer.parseInt(user.get("age").toString()));
if(ret == 0){
result = "插入数据库失败";
}
}
if(userList != null && !userList.isEmpty()){
result = "上传成功";
}else{
result = "上传失败";
}
return result;
} }
dao:
public interface UserDao {
public int insertUser(String name, String sex, int age);
}
daoImpl:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component; import dao.UserDao; @Component
public class UserDaoImpl implements UserDao {
@Autowired(required = true)
private JdbcTemplate jdbcTemplate; @Override
public int insertUser(String name, String sex, int age) {
String sql = "insert into user(name,sex,age) values('"+ name +"','"+ sex +"',"+age+")";
int ret = 0;
try {
ret = jdbcTemplate.update(sql);
} catch (DataAccessException e) {
e.printStackTrace();
}
return ret;
} }
ReadExcel:
package controller; import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile; /**
*
* @author hewangtong
*
*/
public class ReadExcel {
// 总行数
private int totalRows = 0;
// 总条数
private int totalCells = 0;
// 错误信息接收器
private String errorMsg; // 构造方法
public ReadExcel() {
} // 获取总行数
public int getTotalRows() {
return totalRows;
} // 获取总列数
public int getTotalCells() {
return totalCells;
} // 获取错误信息
public String getErrorInfo() {
return errorMsg;
} /**
* 读EXCEL文件,获取信息集合
*
* @param fielName
* @return
*/
public List<Map<String, Object>> getExcelInfo(MultipartFile mFile) {
String fileName = mFile.getOriginalFilename();// 获取文件名
// List<Map<String, Object>> userList = new LinkedList<Map<String, Object>>();
try {
if (!validateExcel(fileName)) {// 验证文件名是否合格
return null;
}
boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
if (isExcel2007(fileName)) {
isExcel2003 = false;
}
return createExcel(mFile.getInputStream(), isExcel2003);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 根据excel里面的内容读取客户信息
*
* @param is 输入流
* @param isExcel2003 excel是2003还是2007版本
* @return
* @throws IOException
*/
public List<Map<String, Object>> createExcel(InputStream is, boolean isExcel2003) {
try {
Workbook wb = null;
if (isExcel2003) {// 当excel是2003时,创建excel2003
wb = new HSSFWorkbook(is);
} else {// 当excel是2007时,创建excel2007
wb = new XSSFWorkbook(is);
}
return readExcelValue(wb);// 读取Excel里面客户的信息
} catch (IOException e) {
e.printStackTrace();
}
return null;
} /**
* 读取Excel里面客户的信息
*
* @param wb
* @return
*/
private List<Map<String, Object>> readExcelValue(Workbook wb) {
// 得到第一个shell
Sheet sheet = wb.getSheetAt(0);
// 得到Excel的行数
this.totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列数(前提是有行数)
if (totalRows > 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
// 循环Excel行数
for (int r = 1; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
// 循环Excel的列
Map<String, Object> map = new HashMap<String, Object>();
for (int c = 0; c < this.totalCells; c++) {
Cell cell = row.getCell(c);
if (null != cell) {
if (c == 0) {
// 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String name = String.valueOf(cell.getNumericCellValue());
map.put("name", name.substring(0, name.length() - 2 > 0 ? name.length() - 2 : 1));// 名称
} else {
map.put("name", cell.getStringCellValue());// 名称
}
} else if (c == 1) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String sex = String.valueOf(cell.getNumericCellValue());
map.put("sex",sex.substring(0, sex.length() - 2 > 0 ? sex.length() - 2 : 1));// 性别
} else {
map.put("sex",cell.getStringCellValue());// 性别
}
} else if (c == 2) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String age = String.valueOf(cell.getNumericCellValue());
map.put("age", age.substring(0, age.length() - 2 > 0 ? age.length() - 2 : 1));// 年龄
} else {
map.put("age", cell.getStringCellValue());// 年龄
}
}
}
}
// 添加到list
userList.add(map);
}
return userList;
} /**
* 验证EXCEL文件
*
* @param filePath
* @return
*/
public boolean validateExcel(String filePath) {
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
errorMsg = "文件名不是excel格式";
return false;
}
return true;
} // @描述:是否是2003的excel,返回true是2003
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
} // @描述:是否是2007的excel,返回true是2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
} }
参考:http://blog.csdn.net/he140622hwt/article/details/78478960
Java导入excel并保存到数据库的更多相关文章
- springMVC(5)---导入excel文件数据到数据库
springMVC(5)---导入excel文件数据到数据库 上一篇文章写了从数据库导出数据到excel文件,这篇文章悄悄相反,写的是导入excel文件数据到数据库.上一篇链接:springMVC(4 ...
- Asp.Net Core 导入Excel数据到Sqlite数据库并重新导出到Excel
Asp.Net Core 导入Excel数据到Sqlite数据库并重新导出到Excel 在博文"在Asp.Net Core 使用 Sqlite 数据库"中创建了ASP.NET Co ...
- java导入excel很完美的取值的方法
java导入excel很完美的取值的方法 1.解决方法: /** * 获取单元格数据内容为字符串类型的数据 * @param cell Excel单元格 * @return St ...
- POI读取Excel数据保存到数据库,并反馈给用户处理信息(导入带模板的数据)
今天遇到这么一个需求,将课程信息以Excel的形式导入数据库,并且课程编号再数据库中不能重复,也就是我们需要先读取Excel提取信息之后保存到数据库,并将处理的信息反馈给用户.于是想到了POI读取文件 ...
- Java 用jxl读取excel并保存到数据库(此方法存在局限,仅限本地电脑操作,放在服务器上的项目,需要把文件上传到服务器,详细信息,见我的别的博客)
项目中涉及到读取excel中的数据,保存到数据库中,用jxl做起来比较简单. 基本的思路: 把excel放到固定盘里,然后前段页面选择文件,把文件的名字传到后台,再利用jxl进行数据读取,把读取到的数 ...
- jsp struts2导入excel并且存储到数据库中
开发中遇到一个问题: 需要从外部导入excel,拿到其中的数据然后保存到数据库中. 1.先在jsp端使用input进行上传: <form action="storeOBDexcel&q ...
- Java Hour 47 WeatherInfo 保存到数据库
经历了上周简单的休整以后,我们继续Hibernate 之旅. 保存到数据库 private void saveWeatherInfo(Weatherinfo weatherInfo) { // Sav ...
- winfrom 导入Excel表到access数据库(来自小抽奖系统)
网上有很多这种方法,本人只是针对自己的系统来实现的 //导入excel表 private void ImportTSMenu_Click(object sender, EventArgs e) { O ...
- java导入Excel表格数据
首先导入Excel数据需要几样东西 第一需要两个依赖包,这里直接是在pom注入依赖 <!--excel--> <dependency> <groupId>org.a ...
随机推荐
- 5.Linux系统的vim与软件包管理
5.1 Linux系统的vim编辑器 5.1.1 vim编辑器的概述 vim编辑器的简介 1.vim是什么? vim是一个类似vi的文本编辑器,它在vi的基础上增加了很多新特性 vim是vi发展出来的 ...
- 10.多shard场景下relevence score可能不准确
主要知识点 多shard场景下relevence score可能不准确的原因 多shard场景下relevence score可能不准确解决方式 一.多shard场景下relevance sc ...
- ssm 数据库连接池配置
1.工程引入druid-1.1.2.jar包2.修改spring-common.xml文件 <!-- 1. 数据源 : DruidDataSource--> <bean id=&qu ...
- 1、ceph-deploy之部署ceph集群
环境说明 server:3台虚拟机,挂载卷/dev/vdb 10G 系统:centos7.2 ceph版本:luminous repo: 公网-http://download.ceph.com,htt ...
- 当前,我们的DJANGO项目的requirements.txt文件
晒一晒,看用得多不多..:) amqp==1.4.7 anyjson==0.3.3 billiard==3.3.0.21 celery==3.1.19 celery-with-redis==3.0 c ...
- [Mini Program] 尺寸单位 rpx
So each phone's width is 750rpx. And according to the device ratio (width:height), we can calucalate ...
- Java 获取随机日期
/** * 获取随机日期 * @param beginDate 起始日期 * @param endDate 结束日期 * @return */ public static Date randomDat ...
- Android中关于内部存储的一些重要函数
一.简介 Android中,你也可以通过绝对路径以JAVA传统方式访问内部存储空间.但是以这种方式创建的文件是对私有,创建它的应用程序对该文件是可读可写,但是别的应用程序并不能直接访问它.不是所有的内 ...
- P1155 双栈排序(二分图染色)
P1155 双栈排序(二分图染色) 题目描述 Tom最近在研究一个有趣的排序问题.如图所示,通过2个栈S1和S2,Tom希望借助以下4种操作实现将输入序列升序排序. 操作a 如果输入序列不为空,将第一 ...
- LuoguP4365 [九省联考2018]秘密袭击
https://zybuluo.com/ysner/note/1141136 题面 求一颗大小为\(n\)的树取联通块的所有方案中,第\(k\)个数之和. \(n\leq1,667,k\leq n\) ...