導入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
