匯入Excel資料到資料庫
阿新 • • 發佈:2018-11-08
java要匯入Excel資料, 那麼首先要讀取Excel 至於 把讀取到的資料存入資料庫 那就很簡單啦 ,略過咯
下面講一講 讀取Excel資料 :
1.首先 要通過磁碟路徑和檔名 獲取Excel檔案,如果檔案不在專案執行的伺服器上,要先把Excel檔案上傳到伺服器指定磁碟下,然後再通過該路徑獲取檔案,直接以流的形式傳輸到後臺也是可以的.
第一步 匯入檔案到java專案執行地
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.szboanda.wdsa.exportData.service.DbResultService; import com.szboanda.wdsa.surfacwater.pjfw.service.SurfacWaterAutoEvaluateService; import net.sf.json.JSONObject; /** * 匯入excel * @author Administrator * */ public class ImportFile { ParseFile parseFile = new ParseFile();//Excel檔案處理層 private String uploadPath = "C:/ImportExcelFile/"; // 上傳檔案的目錄 File tempPathFile; DbResultService dbservice = new DbResultService(); /** *第一步 匯入檔案 * @throws IOException * @throws FileUploadException */ public void importFile(HttpServletRequest req, HttpServletResponse res) throws IOException, FileUploadException{ //接收引數 DiskFileItemFactory factorypage = new DiskFileItemFactory(); ServletFileUpload uploadpage = new ServletFileUpload(factorypage); List<FileItem> itemspage = uploadpage.parseRequest(req); Map<String, String> params = new HashMap<String,String>(); for(Object object:itemspage){ FileItem fileItem = (FileItem) object; if (fileItem.isFormField()) { params.put(fileItem.getFieldName(), fileItem.getString("utf-8"));//如果你頁面編碼是utf-8的 } } //使用params.get獲取引數值 String year = (String) params.get("year"); String month = (String) params.get("month"); String type = (String) params.get("type"); JSONObject obj = new JSONObject(); try { //檢視資料夾是否存在 .如果不存在則建立資料夾 judeDirExists(uploadPath); // 為基於磁碟的檔案項建立工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //設定工廠約束 factory.setSizeThreshold(4096); // 設定緩衝區大小,這裡是4kb factory.setRepository(tempPathFile);// 設定緩衝區目錄 // 建立一個新檔案上傳處理程式 ServletFileUpload upload = new ServletFileUpload(factory); // 設定總體請求大小約束 upload.setSizeMax(4194304); // 設定最大檔案尺寸,這裡是4MB //iterator 迭代器 Iterator<FileItem> i = itemspage.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); String fileName = fi.getName(); if (fileName != null) { //獲取檔案流 File fullFile = new File(new String(fi.getName().getBytes(), "utf-8")); // 解決檔名亂碼問題 //獲取檔名 建立新的檔案 File savedFile = new File(uploadPath, fullFile.getName()); String filename = fullFile.getName(); String filetype = filename.substring(filename.lastIndexOf(".")); //判斷是否為xml字尾的檔案(支援.xls 和.xlsx 兩種格式檔案) if(filetype.equals(".xls")||filetype.equals(".xlsx")){ //在這裡儲存檔案到本地 fi.write(savedFile); getHLData(uploadPath,filename); //讀取Excel檔案方法. } } } //上傳成功 } catch (Exception e) { e.printStackTrace(); } res.getWriter().println(obj); //用來給前端返回匯入情況, 自己視情況寫寫 } // 判斷資料夾是否存在 public static void judeDirExists(String file) { try { if (!(new File(file).isDirectory())) { new File(file).mkdir(); } } catch (SecurityException e) { e.printStackTrace(); } } }
第二部分, 讀取Excel檔案中的資料
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.beanutils.DynaBean; import org.apache.commons.lang.StringUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; 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 com.szboanda.platform.util.BeanUtils; import com.szboanda.platform.util.helper.ActionHelper; import com.szboanda.wdsa.importExcel.importFile.dao.ImportDAO; import jxl.read.biff.BiffException; import net.sf.json.JSONObject; //第二部分, 檢視 public class ParseFile { ImportDAO dao = new ImportDAO(); //讀取excel 用來相容 .xls 和 .xlsx 兩種格式 public static Workbook readExcel(String filePath){ Workbook wb = null; if(filePath==null){ return null; } String extString = filePath.substring(filePath.lastIndexOf(".")); InputStream is = null; try { is = new FileInputStream(filePath); if(".xls".equals(extString)){ return wb = new HSSFWorkbook(is); }else if(".xlsx".equals(extString)){ return wb = new XSSFWorkbook(is); }else{ return wb = null; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return wb; } // 通過檔名和路徑 找到Excel 然後讀取Excel中的資料 public Object getHLData(String filepath, String filename) throws Exception { // 通過檔案的磁碟路徑 獲取檔案流. Workbook wb = readExcel(filepath + filename); // 獲得第一個工作表物件(ecxel中sheet的編號從0開始,0,1,2,3,....) Sheet sheet = wb.getSheetAt(sheetnum); // 行數 int rownum = sheet.getPhysicalNumberOfRows(); //建立list物件 List<Map<String,Object> datalist = new ArrayList<>(); //獲取第0行, 也就是最上面一行, 一般用來做表頭 欄位 Row row0 = sheet.getRow(0); for (int i = 1; i < rownum; i++) { //迴圈獲取Excel中的每行資料 Row row = sheet.getRow(i); //獲取該行的資料列數 int linenum = row.getPhysicalNumberOfCells(); Map<String,Object> map = new HashMap<>(); //獲取該行每一列資料 for (int n = 0; n < linenum ; n++) { //獲取該列欄位名 String linename = row0.getCell(n).toString(); //獲取該行 第0列的資料, 以次類推 String linedata = row.getCell(n).toString(); //建立一個map物件 然後將每一個格的資料放入map中, 然後就可以用來插入資料庫中 map.put(linename,linedata); ****** 此處省略 } datalist.add(map); } //此時獲取的資料都存入datalist中, 然後將datalist 批量插入資料庫即可 dao.insertData(datalist); Object obj = new Object(); return obj;//返回執行結果, 內容自行設定 } }
以上程式碼都是功能主體部分, 其他的操作可自行新增.,,
需要匯入poi的幾個jar包. 到時可搜尋一下