package com.bonus.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Properties; import javax.servlet.http.HttpServletRequest; 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.ss.usermodel.WorkbookFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; @Controller public class ExcelFiledInsertDatabase{ @Autowired private JdbcTemplate jdbcTemplate; private String propertyPath; public String getPropertyPath() { return propertyPath; } public void setPropertyPath(String propertyPath) { this.propertyPath = propertyPath; } @RequestMapping("/insertData") public String mainPage(Model model) { model.addAttribute("tables",getTableNameList()); return "/sys/excelInsertDatabase"; } @RequestMapping(value = "/getColumnListByTitleNumChange") @ResponseBody public List getColumnListByTitleNumChange(HttpServletRequest request,Integer titleNum,String filepath) { List list = new ArrayList(); try { String filePath = request.getSession().getServletContext().getRealPath("/filetemp"); filepath =filePath +"/"+ filepath; list = getExeclColumnList(filepath,titleNum-1); } catch (Exception e) { e.printStackTrace(); } return list; } @RequestMapping(value = "/submitDataToInsert") @ResponseBody public String submitDataToInsert(HttpServletRequest request) { String res = "0"; try { res = insterData(request); } catch (Exception e) { e.printStackTrace(); } return res; } @RequestMapping(value = "/uploadexcel") @ResponseBody public List uploadexcel(HttpServletRequest request,String excelPath) { List list = new ArrayList(); try { list = uploadexcel(request); } catch (Exception e) { e.printStackTrace(); } return list; } @RequestMapping(value = "/getFiledListByTableName") @ResponseBody public List> getFiledListByTableName1(String tableName) { List> list = new ArrayList>(); try { list = getFiledListByTableName(tableName); } catch (Exception e) { e.printStackTrace(); } return list; } public String getDataBaseName(String propertyPath){ Properties prop=new Properties(); InputStream ips=ExcelFiledInsertDatabase.class.getClassLoader() .getResourceAsStream(propertyPath); String[] params = new String[2]; try { prop.load(ips); String property = prop.getProperty("jdbc.mysql.url"); params = property.split("\\?"); System.out.println(params); } catch (Exception e){ e.printStackTrace(); } return params[0].substring(params[0].lastIndexOf("/")+1); } public List> getFiledListByTableName(String tableName) { String sql = "show full columns from "+tableName; List> list = jdbcTemplate.queryForList(sql); return list; } public List getTableNameList() { String dataBaseName = getDataBaseName(propertyPath); String sql = "select table_name from information_schema.tables where table_schema='"+dataBaseName+"'"; List> list = jdbcTemplate.queryForList(sql); List l = new ArrayList(); for(int i=0;i uploadexcel(HttpServletRequest request) { Integer titleNum = Integer.parseInt(request.getParameter("titleNum").toString()); List list = new ArrayList(); String fileName = ""; String filePath = request.getSession().getServletContext().getRealPath("/filetemp"); File file = new File(filePath); if (!file.exists()) { file.mkdirs(); } // 打印上传路径信息 int maxPostSize = 200 * 1024 * 1024; MultipartRequest multi = null; DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy(); try { multi = new MultipartRequest(request, filePath, maxPostSize, "UTF-8", dfp); } catch (IOException e) { e.printStackTrace(); } // 输出反馈信息 Enumeration files = multi.getFileNames(); while (files.hasMoreElements()) { String name = (String) files.nextElement(); File f = multi.getFile(name); if (f != null) { long newName=System.currentTimeMillis(); fileName = multi.getFilesystemName(name); int begin = fileName.indexOf("."); int last = fileName.length(); String suffix = fileName.substring(begin,last); File oldfile = new File(filePath + "/" + fileName); File newfile = new File(filePath + "/" + newName + suffix); oldfile.renameTo(newfile); filePath = filePath + "/" + newName + suffix; list = getExeclColumnList(filePath,titleNum-1); list.add(newName + suffix); //tempFile.delete(); } } return list; } public List getExeclColumnList(String filePath,Integer titleIndex) { List info = new ArrayList(); InputStream is; try { is = new FileInputStream(filePath); Workbook wk = WorkbookFactory.create(is); Sheet st = wk.getSheetAt(0); if(st.getRow(titleIndex) == null){ return info; } int coloumNum=st.getRow(titleIndex).getPhysicalNumberOfCells(); Row row = null; Cell cell = null; row = st.getRow(titleIndex); if(row != null) { for(int j = 0;j> columnStrs = extractExcelFileInfo(filepath,columnStr,start,end); //字段值 String vals = ""; String temp = ""; columnStrs.size(); for(List columnDatas:columnStrs){ temp = "("; for(int i = 0; i < columnDatas.size(); i++){ if(i == 0){ if(columnDatas.get(i) == null || "".equals(columnDatas.get(i)) ){ temp += "null"; }else{ temp += "'"+columnDatas.get(i)+"'"; } }else{ if(columnDatas.get(i) == null || "".equals(columnDatas.get(i)) ){ temp += ",null"; }else{ temp += ",'"+columnDatas.get(i)+"'"; } } } temp += ")"; if("".equals(vals)){ vals = temp; }else{ vals += "," + temp; } } String sql = " insert into "+ tableName +"("+fieldStr+") values"+vals; System.out.println(sql); try { jdbcTemplate.execute(sql); result = "1,"+columnStrs.size();; } catch (Exception e) { e.printStackTrace(); result = "2"; } return result; } public static List> extractExcelFileInfo(String filePath,String columnStr,Integer start,Integer end) { List> info =new ArrayList>(); List list = null; InputStream is; try { String[] indexArr = columnStr.split(","); is = new FileInputStream(filePath); Workbook wk = WorkbookFactory.create(is); Sheet st = wk.getSheetAt(0); int rows = st.getPhysicalNumberOfRows();//行数 Row row = null; Cell cell = null; Integer len = indexArr.length; for(int k = start;k < rows; k++){ row = st.getRow(k); if(row != null){ list = new ArrayList(); for(int i = 0; i