导入excel就是一个上传excel文件,然后获取excel文件数据,然后处理数据并插入到数据库的过程

一、上传excel

前端jsp页面,我的是index.jsp

在页面中我自己加入了一个下载上传文件的功能,其中超链接就是下载

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="jquery/1.7.2/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="jquery/jquery.form.js"></script>
<script type="text/javascript"> function test1(){
var form = new FormData(document.getElementById("uploadForm"));
$.ajax({
contentType:"multipart/form-data",
url:"servlet/UploadHandleServlet",
type:"post",
async:false,
data:form,
dataType:"json",
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success:function(data){
var result=eval(data);
var filePath=result[0].filePath;
//alert(filePath);
var fileName = result[0].imageName;
$("#download").attr("href","servlet/DownLoadServlet?filePath="+filePath);
document.getElementById("download").innerHTML = fileName; //上传文件后得到路径,然后处理数据插入数据库表中
importExcel(filePath);
}
});
} function importExcel(filePath){
$.ajax({
url:"${pageContext.request.contextPath}/user/insertUserByExcelPath",
type:"post",
data:{"filePath":filePath},
success:function(data){
}
});
} </script>
<body> 导入excel表格
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>上传文件:</td>
<td>
<input type="file" name="fileName" id="fileName"/>
</td>
</tr>
</table>
</form>
<button id="uploadFile" onclick="test1();">确定</button>
<!-- servlet/DownLoadServlet -->
上传的文件<a id="download" href=""></a>
</body>
</html>

后端的上传的servlet,其中需要commons-fileupload-1.2.1.jar的支持,然后我的保存路径savePath是自己写的一个配置文件来的,这里可以写上自己的上传文件所保存的路径就行,返回的是一个json,包括文件路径还有文件名

package com.huang.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.UUID; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller; import com.huang.entity.User;
import com.huang.utils.Excel2Bean;
import com.huang.utils.PropertiesUtil; /**
* Servlet implementation class UploadHandleServlet
*/
@WebServlet("/UploadHandleServlet")
public class UploadHandleServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public UploadHandleServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("进入servlet");
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("UTF-8");
// 获取多个上传文件
List fileList = null;
try {
fileList = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 遍历上传文件写入磁盘
Iterator it = fileList.iterator();
while (it.hasNext()) {
Object obit = it.next();
if (obit instanceof DiskFileItem) {
DiskFileItem item = (DiskFileItem) obit;
// 如果item是文件上传表单域
// 获得文件名及路径
String fileName = item.getName();
if (fileName != null) {
String fName = item.getName().substring(
item.getName().lastIndexOf("\\") + 1);
String formatName = fName
.substring(fName.lastIndexOf(".") + 1);// 获取文件后缀名
String savePath = PropertiesUtil.getInstance().getProperty("uploadFile");
// String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
File expsfile = new File(savePath);
if (!expsfile.exists()) {// 创建文件夹
expsfile.mkdirs();
} String realPath = savePath+"/"+ UUID.randomUUID().toString()+"."+formatName;
System.out.println("realPath:"+realPath);
BufferedInputStream bis = new BufferedInputStream(
item.getInputStream());// 获得文件输入流
BufferedOutputStream outStream = new BufferedOutputStream(
new FileOutputStream(new File(realPath)));// 获得文件输出流
Streams.copy(bis, outStream, true);// 开始把文件写到你指定的上传文件夹
// 上传成功,则插入数据库
File file = new File(realPath);
if (file.exists()) {
// request.setAttribute("realPath", realPath);
// request.getRequestDispatcher("/user/insertUserByExcelPath").forward(request, response);
// 返回文件路径
String imageName = file.getName();
String json = "[{\"filePath\":\""
+ realPath
+ "\",\"imageName\":\"" + imageName + "\"}]";
response.reset();
response.setContentType("text/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
// response.getWriter().write(realPath);
response.getWriter().flush();
} }
}
}
} }

二、处理excel表格并得到含有Javabean的list

在用ajax调用servlet上传文件后得到路径和文件名,然后进行excel数据处理,在前端的页面上调用importExcel()的js函数,传入刚刚得到的文件路径

我这里用的是ssm框架中的controller(我自己也学习一下),这里也可以用servlet,或者Struts等。能访问到后端服务就行。

这里是controller中的代码,主要数据处理在Excel2Bean.getBeanByExcelPath(filePath, User.class)这个方法中

import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import javax.annotation.Resource;
import javax.servlet.ServletException;
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.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView; import com.huang.entity.User;
import com.huang.service.UserService;
import com.huang.utils.Excel2Bean; @Controller("/userController")
@RequestMapping("/user")
public class UserController { @Autowired
Excel2Bean excel2Bean; @Resource(name="userService")
UserService userService; @RequestMapping("/insertUserByExcelPath")
public void insertUserByExcelPath(HttpServletRequest req,HttpServletResponse Resp){
System.out.println("进入insertUserByExcelPath");
String filePath = req.getParameter("filePath");
System.out.println("filePath:"+filePath);
List<User> list =Excel2Bean.getBeanByExcelPath(filePath, User.class);
excel2Bean.testinsert(list);
}
}

这里就说说Excel2Bean.getBeanByExcelPath(filePath, User.class)这个方法

从excel表格中获取数据然后转换成一个javaBean的list集合,代码中操作excel表格需要用到的jar poi-ooxml-3.9-20121203.jar,poi-3.9-20121203.jar,poi-ooxml-schemas-3.9-20121203.jar,为什么要用到这些jar,因为在有些之前的版本的poi中可能对word的版本不能兼容,网上具体有说到这个。最好是用org.apache.poi.ss.usermodel.Workbook这个来操作excel,poi各种版本官网下载可以参考微博https://mp.csdn.net/postedit/83620739。对于getBeanByExcelPath这个方法使用到了泛型,也使用到了一点点的反射的东西,获取一个类的属性,并给属性赋值。代码中有方法测试这个获取Javabean的属性并赋值的方法。这个方法也是为了能更通用一点,适用于更多的javabean,更多的表。当然excel的表头就要用到Javabean中的属性名称了。如果对泛型不是很了解的可以学习一下,当然也可以先看里面的readExcel(filePath)这个方法,是一个固定的Javabean对象

代码如下

package com.huang.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*; import javax.annotation.PostConstruct;
import javax.annotation.Resource; import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer; import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.WorkbookFactory;
import org.springframework.stereotype.Component; import com.huang.entity.User;
import com.huang.service.UserService; @Component
public class Excel2Bean { @Resource(name="userService")
UserService userService; public static Excel2Bean excel2Bean; @PostConstruct
public void init() {
excel2Bean = this;
}
public static void testinsert(List<User> list){
if(list!=null&&list.size()>0){
for (User user : list) {
user.setId(excel2Bean.userService.getMaxId()+1);
excel2Bean.userService.insertUserByUser(user);
}
}
// System.out.println(excel2Bean.userService.getMaxId()); } /**
* 获取属性名数组
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* */
public static String[] getFiledName(Class<?> clazz) throws SecurityException, InstantiationException, IllegalAccessException{ Field[] fields=clazz.newInstance().getClass().getDeclaredFields();
String[] fieldNames=new String[fields.length];
for(int i=0;i<fields.length;i++){
// System.out.println(fields[i].getType());
fieldNames[i]=fields[i].getName();
}
return fieldNames;
} public static <T>T getByExcelPath(String excelPath,Class<T> clazz){
T bean = null;
try {
bean = clazz.newInstance();
String tableName = clazz.getSimpleName();
// 反射bean上与列名相同的属性
try {
Field f = bean.getClass().getDeclaredField("name");
f.setAccessible(true);
f.set(bean, "兽王");
// System.out.println(f);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bean;
} public static <T> List<T> getBeanByExcelPath(String excelPath,Class<T> clazz){
List<T> list = new ArrayList<T>();
org.apache.poi.ss.usermodel.Workbook workbook = null;
InputStream is = null;
try {
is = new FileInputStream(excelPath);
workbook = WorkbookFactory.create(is);
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 循环工作表
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
Sheet sheet = workbook.getSheetAt(numSheet);//得到工作表
if (sheet == null) {
continue;
}
// 循环行 因为表头行是第0行,所以从0开始循环
Row rowHead = sheet.getRow(0);
for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
T bean = null;
try {
bean = clazz.newInstance();
} catch (InstantiationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Row row = sheet.getRow(rowNum);//得到行
short s = row.getLastCellNum();//得到此行有多少列
for (int i = 0; i < s; i++) {
Cell cell = row.getCell(i);//得到单元格(每行)
Cell cellHead = rowHead.getCell(i);
String feild = (String) getCellValObject(cellHead);//得到表头属性名称
Object value = getCellValObject(cell);
Field f = null;
try { f = bean.getClass().getDeclaredField(feild);//根据名称获取bean中的属性
f.setAccessible(true);
f.set(bean, value);//给属性赋值
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} //把所有属性值添加完成后装入list中
list.add(bean); }
} return list;
} public static String getCellVal(HSSFCell cel) {
if(cel.getCellType() == HSSFCell.CELL_TYPE_STRING) {
return cel.getRichStringCellValue().getString();
}
if(cel.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
return cel.getNumericCellValue() + "";
}
if(cel.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
return cel.getBooleanCellValue() + "";
}
return cel.toString();
} public static String getCellVal(Cell cel) {
if(cel.getCellType() == Cell.CELL_TYPE_STRING) {
return cel.getRichStringCellValue().getString();
}
if(cel.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return cel.getNumericCellValue() + "";
}
if(cel.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return cel.getBooleanCellValue() + "";
}
if(cel.getCellType() == Cell.CELL_TYPE_FORMULA) {
return cel.getCellFormula() + "";
}
return cel.toString();
} public static Object getCellValObject(Cell cel) {
if(cel.getCellType() == Cell.CELL_TYPE_STRING) {
return cel.getRichStringCellValue().getString();
}
if(cel.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return new Integer(Double.valueOf(cel.getNumericCellValue()).intValue());
}
if(cel.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return cel.getBooleanCellValue() + "";
}
if(cel.getCellType() == Cell.CELL_TYPE_FORMULA) {
return cel.getCellFormula() + "";
}
return null;
} public static List<User> readExcel(String filePath){
List<User> list = new ArrayList<User>();
// HSSFWorkbook workbook = null;
org.apache.poi.ss.usermodel.Workbook workbook = null;
try {
// 读取Excel文件
InputStream inputStream = new FileInputStream(filePath);
// workbook = new HSSFWorkbook(inputStream);
workbook = WorkbookFactory.create(inputStream);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// 循环工作表
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
Sheet hssfSheet = workbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循环行
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
Row hssfRow = hssfSheet.getRow(rowNum);
// System.out.println("hssfRow1:"+hssfRow.getRowNum());
// System.out.println("hssfRow2:"+hssfRow.getLastCellNum());
if (hssfRow == null) {
continue;
}
// 将单元格中的内容存入集合
User user = new User();
Cell cell = hssfRow.getCell(0);
if (cell == null) {
continue;
}
String name = getCellVal(cell);
System.out.println("name:"+name);
user.setName(name);
cell = hssfRow.getCell(1);
if (cell == null) {
continue;
}
String age = getCellVal(cell);
Integer aa = Double.valueOf(age).intValue(); System.out.println("age:"+age);
user.setAge(Double.valueOf(age).intValue());
list.add(user);
}
}
return list;
}
}

三、插入数据库

得到excel转换成Javabean的list对象后然后插入到数据库中。我这里用的是ssm里面的一些操作,我自己可能都解释不清楚。反正得到数据,然后往数据库插入数据这个操作也可以用其他方式的,框架也好,jdbc连接数据库直接去执行sql也好,都OK。

最后贴一下下载上传的文件的servlet代码

package com.huang.servlet;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class DownLoadServlet
*/
@WebServlet("/DownLoadServlet")
public class DownLoadServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public DownLoadServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 下载文件
// String path = "d:"+File.separator + "mytestfile" + File.separator + "testFile.txt";
String path = request.getParameter("filePath");
String realPath = path.substring(path.lastIndexOf("\\")+1);
response.setHeader("content-disposition","attachment; filename="+URLEncoder.encode(realPath, "utf-8"));
//获取到所下载的资源
FileInputStream fis = new FileInputStream(path);
if(fis!=null){
int len = 0;
byte[] buf = new byte[1024];
while ((len = fis.read(buf)) != -1) {
response.getOutputStream().write(buf, 0, len);
}
fis.close();
}else{
response.getWriter().write("服务器上面不存在该文件");
} } }

还有User.java这个javabean、

public class User {
private Integer id; private String name; private Integer age; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name == null ? null : name.trim();
}

原文链接:https://blog.csdn.net/summerdirewof/article/details/83822710

java实现excel表格导入数据库表的更多相关文章

  1. C#解决从含身份证号码的Excel表格导入数据库的问题

    用C#做从Excel表导入SQL数据库时发现从EXCEL导入的身份证号码会变成科学表示方法. 解决这个问题是比较容易的,首先,打开电子表格,选中“身份证号码”一列,右键选择“设置单元格格式”,进入单元 ...

  2. SQL语句完成Excel数据导入数据库表中流程方法及注意事项

    第一步:先查看数据库是否安装AccessDatabaseEngine_X64.exe, 如下图查看: 如果未安装先下载脚本之家下载地址 https://www.jb51.net/softs/29150 ...

  3. excel表格导入数据库数据存在则更新不存在添加

    public void excelToDB() throws ParseException { String datapath = this.getParameter("datapath&q ...

  4. C#代码实现 Excel表格与Object互相转换,Excel表格导入数据库(.NET2.0 .NET4.0)

    前些天在工作上遇到这个需求,在GitHub找到一个开源代码可以用,Fork了一个版本,整理一下发出来. ①.Net项目中使用Nuget安装一个 NPOI 包    https://github.com ...

  5. Excel表格导入Mysql数据库,一行存入多条数据的前后台完整实现思路(使用mybatis框架)

    现在有一张Excel表格: 存入数据库时需要这样存放: 现在需要将Excel表格做处理,将每一行拆分成多条数据存入数据库. 1.首先在前台jsp页面画一个按钮:,加入点击事件: <td styl ...

  6. JAVA处理Excel表格数据并写入数据库

    package com.hncj.test; import java.io.FileInputStream; import java.sql.Connection; import java.sql.D ...

  7. java导出excel表格

    java导出excel表格: 1.导入jar包 <dependency> <groupId>org.apache.poi</groupId> <artifac ...

  8. java实现excel的导入导出(poi详解)[转]

    java实现excel的导入导出(poi详解) 博客分类: java技术 excel导出poijava  经过两天的研究,现在对excel导出有点心得了.我们使用的excel导出的jar包是poi这个 ...

  9. Java读取excel表格

    Java读取excel表格 一般都是用poi技术去读取excel表格的,但是这个技术又是什么呢 什么是Apache POI? Apache POI是一种流行的API,它允许程序员使用Java程序创建, ...

随机推荐

  1. Docker从入门到精通(八)——Docker Compose

    恭喜大家,学到这里,对于 docker 的基础玩法大家应该都会了,下面会介绍 docker的一些编排工具. 1.为什么需要 Docker Compose? 官网镇楼:https://www.runoo ...

  2. libevent源码学习(6):事件处理基础——event_base的创建

    目录前言创建默认的event_baseevent_base的配置event_config结构体创建自定义event_base--event_base_new_with_config禁用(避免使用)某一 ...

  3. 除了背八股文,Java面试更该这样准备

    我可以这样说,哪怕你背了再多java八股文的答案,过面试也能靠运气,因为很多java面试的答案只限于技术理论说辞.但用我本文给出的方法去准备面试,能在不提升技术的前提下,大大提升你java面试的通过率 ...

  4. SpringBoot简单整合Actuator监控

    pom依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>s ...

  5. SpringBoot 整合es(elasticsearch)使用elasticsearch-rest-high-level-client实现增删改

    引入依赖 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok< ...

  6. table中tr、td标签设置只读,不能修改(readonly属性)

    在不能修改的位置加上代码:onselectstart="return false" οnselect="document.selection.empty()" ...

  7. 利用免费二维码API自动生成网址图片二维码

    调用第三方接口生成二维码 官方地址:http://goqr.me/api/ 示例 https://api.qrserver.com/v1/create-qr-code/?size=180x180&am ...

  8. 【九度OJ】题目1182:统计单词 解题报告

    [九度OJ]题目1182:统计单词 解题报告 标签(空格分隔): 九度OJ http://ac.jobdu.com/problem.php?pid=1182 题目描述: 编一个程序,读入用户输入的,以 ...

  9. 【LeetCode】299. Bulls and Cows 解题报告(Python)

    [LeetCode]299. Bulls and Cows 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题 ...

  10. codeforces 624C Graph and String

    C. Graph and String time limit per test 2 seconds memory limit per test 256 megabytes input standard ...