1. Page example
2. Excel sample (the following figure does not need to delete the row)
3. Set the upload file size in the Spring configuration file
<!--Upload file bean configuration--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--Set upload file size--> <property name="maxInMemorySize" value="5000000"/> </bean>
Fourth, edit jsp (knowledge.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <% String importMsg = ""; if (request.getSession().getAttribute("msg") != null) { importMsg = request.getSession().getAttribute("msg").toString(); } request.getSession().setAttribute("msg", ""); %> <head> <title>Knowledge Base</title> <style> body{ padding-top: 70px; padding-left: 190px; } </style> <script src="${pageContext.request.contextPath}/static/js/jquery-1.11.1.min.js"></script> <script type="text/javascript"> function check() { var excel_file = $("#excel_file").val(); if (excel_file == "" || excel_file.length == 0) { alert("Please select the file path!"); return false; } else { return true; } } $(document).ready(function() { var msg = ""; if ($("#importMsg").text() != null) { msg = $("#importMsg").text(); } if (msg != "") { alert(msg); } }); </script> </head> <body> <form action="knowledge/fileDown" method="get"> <input type="submit" value="下载模板"> </form> <div> <font color="blue">Import customers in bulk</font> </div> <form action="knowledge/uploadFile" method="post" enctype="multipart/form-data" onsubmit="return check();"> <div style="margin: 30px;"> <input id="excel_file" type="file" name="filename" accept="xlsx" size="80" /> <input id="excel_button" type="submit" value="导入Excel" /> </div> <font id="importMsg" color="red"><%=importMsg%></font><input type="hidden" /> </form> </body> </html>
5. Edit the java file
5.1 Tool code ( WDWUtil.java ) (need to judge the Excel version, different versions have different suffixes)
public class WDWUtil { // @Description: Whether it is 2003 excel, return true is 2003 public static boolean isExcel2003(String filePath) { return filePath.matches("^.+\\.(?i)(xls)$"); } //@Description: Whether it is 2007 excel, return true is 2007 public static boolean isExcel2007(String filePath) { return filePath.matches("^.+\\.(?i)(xlsx)$"); } }
5.2 Tool class code ( ReadExcel.java )
Generally speaking, the file uploaded by the client user is copied to the local disk of the server, and then read from the copied file, so as to avoid the problem of reading due to the abnormal network of the client or other conditions. data loss or corruption.
import com.wk.model.TKnowledge; 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; import org.springframework.web.multipart.commons.CommonsMultipartFile; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * Created by 锴 on 2018/3/4. */ public class ReadExcel { //total number of rows private int totalRows = 0; //total number private int totalCells = 0; //error message receiver private String errorMsg; //Construction method public ReadExcel(){} //get the total number of rows public int getTotalRows() { return totalRows;} //get the total number of columns public int getTotalCells () {return totalCells;} //get error message public String getErrorInfo() { return errorMsg; } /** * Verify EXCEL files * @param filePath * @return */ public boolean validateExcel(String filePath){ if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))){ errorMsg = "The file name is not in excel format"; return false; } return true; } /** * Read EXCEL file, get customer information collection * @param fileName * @return */ public List<TKnowledge> getExcelInfo(String fileName, MultipartFile Mfile){ //Convert the MultipartFile uploaded by the spring file to the CommonsMultipartFile type CommonsMultipartFile cf= (CommonsMultipartFile)Mfile; //Get the local storage path File file = new File("C:\\fileupload"); //Create a directory (its pathname is specified by the current File object, including any required parent paths.) if (!file.exists()) file.mkdirs(); // create a new file // File file1 = new File("C:\\fileupload" + new Date().getTime() + ".xlsx"); File file1 = new File("C:\\fileupload" + File.separator + fileName); //Write the uploaded file to the newly created file try { cf.getFileItem().write(file1); } catch (Exception e) { e.printStackTrace (); } //Initialize the collection of customer information List<TKnowledge> knowledgeList=new ArrayList<TKnowledge>(); //Initialize the input stream InputStream is = null; try{ // Verify that the file name is valid if(!validateExcel(fileName)){ return null; } / / Determine whether the file is the 2003 version or the 2007 version according to the file name boolean isExcel2003 = true; if(WDWUtil.isExcel2007(fileName)){ isExcel2003 = false; } //Instantiate the input stream based on the newly created file is = new FileInputStream(file1); //Read customer information according to the content in excel knowledgeList = getExcelInfo(is, isExcel2003); is.close(); }catch(Exception e){ e.printStackTrace (); } finally{ if(is !=null) { try{ is.close(); }catch(IOException e){ is = null; e.printStackTrace (); } } } return knowledgeList; } /** * Read customer information according to the content in excel * @param is the input stream * @param isExcel2003 excel is the 2003 or 2007 version * @return * @throws IOException */ public List<TKnowledge> getExcelInfo(InputStream is,boolean isExcel2003){ List<TKnowledge> knowledgeList=null; try{ /** Choose the way to create a Workbook according to the version */ Workbook wb = null; // when excel is 2003 if(isExcel2003){ wb = new HSSFWorkbook(is); } else{//When excel is 2007 wb = new XSSFWorkbook(is); } //Read customer information in Excel knowledgeList=readExcelValue(wb); } catch (IOException e) { e.printStackTrace (); } return knowledgeList; } /** * Read customer information in Excel * @param wb * @return */ private List<TKnowledge> readExcelValue(Workbook wb){ // get the first shell Sheet sheet=wb.getSheetAt(0); //Get the number of rows in Excel this.totalRows=sheet.getPhysicalNumberOfRows(); //Get the number of columns in Excel (provided there are rows) if(totalRows>=1 && sheet.getRow(0) != null){ this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells(); } List<TKnowledge> customerList=new ArrayList<TKnowledge>(); TKnowledge knowledge; // Loop the number of Excel rows, starting from the second row. Title not in stock for(int r=1;r<totalRows;r++){ Row row = sheet.getRow(r); if (row == null) continue; knowledge = new TKnowledge(); //loop through the columns of Excel for(int c = 0; c <this.totalCells; c++){ Cell cell = row.getCell(c); if (null != cell){ if(c==0){ knowledge.setQuestion1(cell.getStringCellValue());//问题 knowledge.setSolveNum(0); knowledge.setUnsolveNum(0); knowledge.setUseNum(0); }else if(c==1){ knowledge.setAnswer(cell.getStringCellValue());//答案 }else if(c==2){ knowledge.setQuestion2(cell.getStringCellValue());//Similar question 1 }else if(c==3){ knowledge.setQuestion3(cell.getStringCellValue());//Similar question 2 }else if(c==4){ knowledge.setQuestion4(cell.getStringCellValue());//Similar question 3 }else if(c==5){ knowledge.setQuestion5(cell.getStringCellValue());//Similar question 4 }else if(c==6){ knowledge.setQuestion6(cell.getStringCellValue());//Similar question 5 } } } //add knowledge customerList.add(knowledge); } return customerList; } }
5.3 Service layer code (KnowledgeService.java)
@Resource private TKnowledgeMapper knowledgeMapper; @Override public boolean batchImort(String name, MultipartFile file) { boolean b = false; //Create and handle EXCEL ReadExcel readExcel=new ReadExcel(); //Parse excel to get a collection of customer information. List<TKnowledge> knowledgeList = readExcel.getExcelInfo(name ,file); if(knowledgeList != null){ b = true; } //Add customer information iteratively (Note: In fact, you can also directly use the customerList collection as a parameter here, and use the foreach tag in the corresponding mapping file of Mybatis to add it in batches.) for(TKnowledge knowledge:knowledgeList){ knowledgeMapper.insert(knowledge); } return b; } @Override public int insert(TKnowledge record) { return knowledgeMapper.insert(record);//Insert a piece of data }
5.4 Controller code (KnowledgeController.java)
@Controller @RequestMapping("/web/knowledge") public class KnowledgeController { @Resource private KnowledgeService knowledgeService; @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public String uploadFile(@RequestParam(value = "filename") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("Start uploading files"); //Check if the file is empty if (file == null) return null; //get filename String name = file.getOriginalFilename(); //Further judge whether the file is empty (that is, judge whether its size is 0 or whether its name is null) long size = file.getSize(); if (name == null || ("").equals(name) && size == 0) return null; //Batch Import. Parameters: filename, file. boolean b = knowledgeService.batchImort(name, file); if (b) { String Msg = "Batch import EXCEL successful!"; request.getSession().setAttribute("msg", Msg); } else { String Msg = "Failed to batch import EXCEL!"; request.getSession().setAttribute("msg", Msg); } return "web/knowledge"; } @RequestMapping(value = "/fileDown", method = RequestMethod.GET) public void down(HttpServletRequest request, HttpServletResponse response) throws Exception { //Simulation file, myfile.txt is the file that needs to be downloaded String fileName = request.getSession().getServletContext().getRealPath("static/file/knowledge base import template.xls"); System.out.println(fileName); //get the input stream InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName))); //If it is downloaded in Chinese name String filename = "Knowledge Base Import Template.xls"; //Transcoding, so as to avoid Chinese garbled file name filename = URLEncoder.encode(filename,"UTF-8"); //Set the file download header response.addHeader("Content-Disposition", "attachment;filename=" + filename); //1. Set the file ContentType type, so setting, will automatically determine the download file type response.setContentType("multipart/form-data"); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); int len = 0; while((len = bis.read()) != -1){ out.write(len); out.flush(); } out.close(); } }
6. Finally, the project structure is attached
This blog ignores the model layer code, the tool class and model layer can be changed according to requirements