日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

java实现excel表格导入数据库表

發(fā)布時間:2024/1/1 数据库 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java实现excel表格导入数据库表 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

導(dǎo)入excel就是一個上傳excel文件,然后獲取excel文件數(shù)據(jù),然后處理數(shù)據(jù)并插入到數(shù)據(jù)庫的過程

一、上傳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不要去處理發(fā)送的數(shù)據(jù)contentType: false, // 告訴jQuery不要去設(shè)置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; //上傳文件后得到路徑,然后處理數(shù)據(jù)插入數(shù)據(jù)庫表中importExcel(filePath); }}); }function importExcel(filePath){$.ajax({url:"${pageContext.request.contextPath}/user/insertUserByExcelPath",type:"post",data:{"filePath":filePath},success:function(data){}}); }</script> <body>導(dǎo)入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("進(jìn)入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 blocke.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()) {// 創(chuàng)建文件夾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);// 開始把文件寫到你指定的上傳文件夾// 上傳成功,則插入數(shù)據(jù)庫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調(diào)用servlet上傳文件后得到路徑和文件名,然后進(jìn)行excel數(shù)據(jù)處理,在前端的頁面上調(diào)用importExcel()的js函數(shù),傳入剛剛得到的文件路徑

我這里用的是ssm框架中的controller(我自己也學(xué)習(xí)一下),這里也可以用servlet,或者Struts等。能訪問到后端服務(wù)就行。

這里是controller中的代碼,主要數(shù)據(jù)處理在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 {@AutowiredExcel2Bean excel2Bean;@Resource(name="userService")UserService userService;@RequestMapping("/insertUserByExcelPath")public void insertUserByExcelPath(HttpServletRequest req,HttpServletResponse Resp){System.out.println("進(jìn)入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表格中獲取數(shù)據(jù)然后轉(zhuǎn)換成一個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的版本不能兼容,網(wǎng)上具體有說到這個。最好是用org.apache.poi.ss.usermodel.Workbook這個來操作excel,poi各種版本官網(wǎng)下載可以參考微博CSDN。對于getBeanByExcelPath這個方法使用到了泛型,也使用到了一點(diǎn)點(diǎn)的反射的東西,獲取一個類的屬性,并給屬性賦值。代碼中有方法測試這個獲取Javabean的屬性并賦值的方法。這個方法也是為了能更通用一點(diǎn),適用于更多的javabean,更多的表。當(dāng)然excel的表頭就要用到Javabean中的屬性名稱了。如果對泛型不是很了解的可以學(xué)習(xí)一下,當(dāng)然也可以先看里面的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;@PostConstructpublic 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());}/** * 獲取屬性名數(shù)組 * @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 blocke.printStackTrace();} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.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 blocke.printStackTrace();} catch (InvalidFormatException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} // 循環(huán)工作表for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {Sheet sheet = workbook.getSheetAt(numSheet);//得到工作表if (sheet == null) {continue;}// 循環(huán)行 因為表頭行是第0行,所以從0開始循環(huán)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 blocke1.printStackTrace();} catch (IllegalAccessException e1) {// TODO Auto-generated catch blocke1.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);//根據(jù)名稱獲取bean中的屬性f.setAccessible(true);f.set(bean, value);//給屬性賦值} catch (NoSuchFieldException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} }//把所有屬性值添加完成后裝入list中l(wèi)ist.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();}// 循環(huán)工作表for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {Sheet hssfSheet = workbook.getSheetAt(numSheet);if (hssfSheet == null) {continue;}// 循環(huán)行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;}// 將單元格中的內(nèi)容存入集合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;} }

三、插入數(shù)據(jù)庫

得到excel轉(zhuǎn)換成Javabean的list對象后然后插入到數(shù)據(jù)庫中。需要自己去實現(xiàn)UserService 的insertUserByUser方法。反正得到數(shù)據(jù),然后往數(shù)據(jù)庫插入數(shù)據(jù)這個操作也可以用其他方式的,框架也好,jdbc連接數(shù)據(jù)庫直接去執(zhí)行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("服務(wù)器上面不存在該文件");}}}

還有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();}

頁面效果如下,超鏈接可以下載,點(diǎn)擊確定后上傳文件并取數(shù)據(jù)然后插入數(shù)據(jù)庫表中?

excel表格形式如下?

nameage
大魚18
小魚15

文章不知道有什么遺漏的地方,有的話,還請多多指教。

總結(jié)

以上是生活随笔為你收集整理的java实现excel表格导入数据库表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。