java读取excel中的数据存到数据库
1.導入jar包
<!-- poi -->
?? ??? ?<dependency>
?? ??? ??? ?<groupId>org.apache.poi</groupId>
?? ??? ??? ?<artifactId>poi</artifactId>
?? ??? ??? ?<version>3.11</version>
?? ??? ?</dependency>
?? ??? ?<dependency>
?? ??? ??? ?<groupId>org.apache.poi</groupId>
?? ??? ??? ?<artifactId>poi-examples</artifactId>
?? ??? ??? ?<version>3.17</version>
?? ??? ?</dependency>
?? ??? ?<dependency>
?? ??? ??? ?<groupId>org.apache.poi</groupId>
?? ??? ??? ?<artifactId>poi-excelant</artifactId>
?? ??? ??? ?<version>3.17</version>
?? ??? ?</dependency>
2.配置下載模板
在controller中寫下載模板接口:
@Controller
@RequestMapping(value = "/excelModel")
public class PoiExpExcel {
? ??
? ? @RequestMapping(value = "/importExcelModel", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
? ? @ResponseBody
? ? public ModelAndView exportExcel()throws Exception{?
? ? ? ? ModelAndView mv = new ModelAndView(); ?
? ? ? ? Map<String,Object> dataMap = new HashMap<String,Object>(); ?
? ? ? ? List<String> titles = new ArrayList<String>(); ?
? ? ? ? titles.add("油站編號"); ?
? ? ? ? titles.add("所屬省份"); ?
? ? ? ? titles.add("所屬城市");
? ? ? ? titles.add("所屬片區"); ?
? ? ? ? titles.add("非油品編碼"); ?
? ? ? ? titles.add("油站名");?
? ? ? ? titles.add("油站類型");?
? ? ? ? titles.add("具體位置");?
? ? ? ? titles.add("電話(含區號)");?
? ? ? ? titles.add("營業時間");?
? ? ? ? titles.add("營業/關停");?
? ? ? ? titles.add("是否有充值業務");?
? ? ? ? titles.add("是否有便利店");?
? ? ? ? titles.add("經度");?
? ? ? ? titles.add("緯度");?
? ? ? ? titles.add("92#");?
? ? ? ? titles.add("95#");?
? ? ? ? titles.add("98#");?
? ? ? ? titles.add("0#");?
? ? ? ? dataMap.put("titles", titles); ?
? ? ? ? ObjectExcelView erv = new ObjectExcelView(); ?
? ? ? ? mv = new ModelAndView(erv,dataMap); ?
? ? ? ? ? ?return mv; ? ?} ?
}
在接口中使用了工具類ObjectExcelView:
public class ObjectExcelView extends AbstractExcelView{
? ??
? ? @Override ?
? ? protected void buildExcelDocument(Map<String, Object> model, ?
? ? ? ? ? ? HSSFWorkbook workbook, HttpServletRequest request, ?
? ? ? ? ? ? HttpServletResponse response) throws Exception { ?
? ? ? ? // TODO Auto-generated method stub ?
? ? ? ? Date date = new Date();
? ? ? ? String filename = Tools.date2Str(date, "yyyyMMddHHmmss");
? ? ? ? HSSFSheet sheet; ?
? ? ? ? HSSFCell cell; ?
? ? ? ? response.setContentType("application/octet-stream"); ?
? ? ? ? response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls"); ?
? ? ? ? sheet = workbook.createSheet("sheet1");?
? ? ? ??
? ? ? ? List<String> titles = (List<String>) model.get("titles"); ?
? ? ? ? int len = titles.size(); ?
? ? ? ? HSSFCellStyle headerStyle = workbook.createCellStyle(); //標題樣式 ?
? ? ? ? headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); ?
? ? ? ? headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); ?
? ? ? ? HSSFFont headerFont = workbook.createFont(); ? ?//標題字體 ?
? ? ? ? headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); ?
? ? ? ? headerFont.setFontHeightInPoints((short)11); ?
? ? ? ? headerStyle.setFont(headerFont); ?
? ? ? ? short width = 20,height=25*20; ?
? ? ? ? sheet.setDefaultColumnWidth(width); ?
? ? ? ? HSSFRow row=sheet.createRow(0);
? ? ? ? for(int i=0; i<len; i++){ //設置標題 ?
? ? ? ? ? ? String title = titles.get(i);
? ? ? ? ? ? ? ? if(title.equals("模板使用教程")) {
? ? ? ? ? ? ? ? HSSFCell createCell = row.createCell(i);
? ? ? ? ? ? ? ? //createCell.setCellValue("模板使用說明: 在油站類型列 ?1-中石油,2-中石化,3-其它加油站"+"\n");
? ? ? ? ? ? ? ? createCell.setCellValue("模板使用說明: 在油站類型列 ?1-中石油,2-中石化,3-其它加油站");
? ? ? ? ? ? ? ? HSSFCellStyle style=workbook.createCellStyle();
? ? ? ? ? ? ? ? style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
? ? ? ? ? ? ? ? style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
? ? ? ? ? ? ? ? style.setWrapText(true);//自動換行
? ? ? ? ? ? ? ? style.setIndention((short)3);//縮進
? ? ? ? ? ? ? ? HSSFFont font = workbook.createFont();
? ? ? ? ? ? ? ? font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
? ? ? ? ? ? ? ? font.setColor(Font.COLOR_RED);//設置字體顏色
? ? ? ? ? ? ? ? style.setFont(font);
? ? ? ? ? ? ? ? createCell.setCellStyle(style);
? ? ? ? ? ? ? ? //設置合并單元格,第一個參數:起始行號;第二個參數:結束行號;第三個參數:起始列號;第四個參數:結束列號;
? ? ? ? ? ? ? ? CellRangeAddress region=new CellRangeAddress(0, 3, i, i+1);
? ? ? ? ? ? ? ? sheet.addMergedRegion(region);
? ? ? ? ? ? ? ? ?
? ? ? ? ? ? }else {
? ? ? ? ? ? ? ? cell = getCell(sheet, 0, i); ?
? ? ? ? ? ? ? ? cell.setCellStyle(headerStyle); ?
? ? ? ? ? ? ? ? setText(cell,title);
? ? ? ? ? ? }
? ? ? ? ?/*if(title.equals("車輛類型")) {
? ? ? ? ? ? ?CellRangeAddressList regions = new CellRangeAddressList(1, 65535,i, i);
? ? ? ? ? ? ?DVConstraint constraint =DVConstraint.createExplicitListConstraint(new String[] { "轎車","貨運", "客車","工程車","卡車","SUV","MVP","油品運輸車","燃氣運輸車"});
? ? ? ? ? ? ?HSSFDataValidation dataValidate = new HSSFDataValidation(regions,constraint);
? ? ? ? ? ? ? sheet.addValidationData(dataValidate); ? ?
? ? ? ? ? ? ?}
? ? ? ? ?if(title.equals("油品類型")) {
? ? ? ? ? ? ?CellRangeAddressList regions = new CellRangeAddressList(1, 65535,i, i);
? ? ? ? ? ? ?DVConstraint constraint =DVConstraint.createExplicitListConstraint(new String[] {"92#", "95#","98#", "5#","0#","-10#","-20#"});
? ? ? ? ? ? ?HSSFDataValidation dataValidate = new HSSFDataValidation(regions,constraint);
? ? ? ? ? ? ? sheet.addValidationData(dataValidate); ? ?
? ? ? ? ? ? ?}
? ? ? ? ?if(title.equals("車輛等級")) {
? ? ? ? ? ? ?CellRangeAddressList regions = new CellRangeAddressList(1, 65535,i, i);
? ? ? ? ? ? ?DVConstraint constraint =DVConstraint.createExplicitListConstraint(new String[] { "黑卡","鉆石卡", "白金卡","黃金卡","白銀卡","普通卡"});
? ? ? ? ? ? ?HSSFDataValidation dataValidate = new HSSFDataValidation(regions,constraint);
? ? ? ? ? ? ? sheet.addValidationData(dataValidate); ? ?
? ? ? ? ? ? ?}*/
? ? ? ? ? ? ??
? ? ? ? } ?
? ? ? ? sheet.getRow(0).setHeight(height); ? ?
? ? ? ? HSSFCellStyle contentStyle = workbook.createCellStyle(); //內容樣式 ?
? ? ? ? contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); ?
? ? ? ??
? ? ? ? List<PageData> varList = (List<PageData>) model.get("varList"); ?
? ? if(varList!=null) {
? ? ? ? int varCount = varList.size(); ?
? ? ? ? for(int i=0; i<varCount; i++){ ?
? ? ? ? ? ? PageData vpd = varList.get(i); ?
? ? ? ? ? ? for(int j=0;j<len;j++){ ?
? ? ? ? ? ? ? ? String varstr = vpd.getString("var"+(j+1)) != null ? vpd.getString("var"+(j+1)) : ""; ?
? ? ? ? ? ? ? ? cell = getCell(sheet, i+1, j); ?
? ? ? ? ? ? ? ? cell.setCellStyle(contentStyle); ?
? ? ? ? ? ? ? ? setText(cell,varstr); ?
? ? ? ? ? ? } ?
? ? ? ? ? ? ??
? ? ? ? } ?}
? ? ? ? ??
? ? } ?
}
3.配置工具類ObjectExcelView引用的PageData工具類:
@SuppressWarnings("all")
public class PageData extends HashMap implements Map{
? ? private static final long serialVersionUID = 1L;
? ? Map map = null;
? ? HttpServletRequest request;
? ? public PageData(HttpServletRequest request){
? ? ? ? this.request = request;
? ? ? ? Map properties = request.getParameterMap();
? ? ? ? Map returnMap = new HashMap();
? ? ? ? Iterator entries = properties.entrySet().iterator();
? ? ? ? Map.Entry entry;
? ? ? ? String name = "";
? ? ? ? String value = "";
? ? ? ? while (entries.hasNext()) {
? ? ? ? ? ? entry = (Map.Entry) entries.next();
? ? ? ? ? ? name = (String) entry.getKey();
? ? ? ? ? ? System.out.println(name);
? ? ? ? ? ? Object valueObj = entry.getValue();
? ? ? ? ? ? if(null == valueObj){
? ? ? ? ? ? ? ? value = "";
? ? ? ? ? ? }else if(valueObj instanceof String[]){
? ? ? ? ? ? ? ? String[] values = (String[])valueObj;
? ? ? ? ? ? ? ? for(int i=0;i<values.length;i++){
? ? ? ? ? ? ? ? ? ? value = values[i] + ",";
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? value = value.substring(0, value.length()-1);
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? value = valueObj.toString();
? ? ? ? ? ? }
? ? ? ? ? ? returnMap.put(name, value);
? ? ? ? }
? ? ? ? map = returnMap;
? ? }
? ? public PageData() {
? ? ? ? map = new HashMap();
? ? }
? ? @Override
? ? public Object get(Object key) {
? ? ? ? Object obj = null;
? ? ? ? if(map.get(key) instanceof Object[]) {
? ? ? ? ? ? Object[] arr = (Object[])map.get(key);
? ? ? ? ? ? obj = request == null ? arr:(request.getParameter((String)key) == null ? arr:arr[0]);
? ? ? ? } else {
? ? ? ? ? ? obj = map.get(key);
? ? ? ? }
? ? ? ? return obj;
? ? }
? ? public String getString(Object key) {
? ? ? ? return (String)get(key);
? ? }
? ? @Override
? ? public Object put(Object key, Object value) {
? ? ? ? return map.put(key, value);
? ? }
? ? @Override
? ? public Object remove(Object key) {
? ? ? ? return map.remove(key);
? ? }
? ? public void clear() {
? ? ? ? map.clear();
? ? }
? ? public boolean containsKey(Object key) {
? ? ? ? return map.containsKey(key);
? ? }
? ? public boolean containsValue(Object value) {
? ? ? ? return map.containsValue(value);
? ? }
? ? public Set entrySet() {
? ? ? ? return map.entrySet();
? ? }
? ? public boolean isEmpty() {
? ? ? ? return map.isEmpty();
? ? }
? ? public Set keySet() {
? ? ? ? return map.keySet();
? ? }
? ? @SuppressWarnings("unchecked")
? ? public void putAll(Map t) {
? ? ? ? map.putAll(t);
? ? }
? ? public int size() {
? ? ? ? return map.size();
? ? }
? ? public Collection values() {
? ? ? ? return map.values();
? ? }
}
?
4.配置工具類ReadExcel讀取excel中的內容:
@Component
public class ReadExcel {
? //總行數
? ? private int totalRows = 0; ?
? ? //總條數
? ? private int totalCells = 0;?
? ? //錯誤信息接收器
? ? private String errorMsg;
? ? //構造方法
? ? public ReadExcel(){}
? ? //獲取總行數
? ? public int getTotalRows() ?{ return totalRows;}?
? ? //獲取總列數
? ? public int getTotalCells() { ?return totalCells;}?
? ? //獲取錯誤信息
? ? public String getErrorInfo() { return errorMsg; } ?
// ? ?@Value("${PICTURE_ADDR}")
// ? ?public String PICTURE_ADDR;
? ??
? /**
? ?* 驗證EXCEL文件
? ?* @param filePath
? ?* @return
? ?*/
? public boolean validateExcel(String filePath){
? ? ? ? if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))){ ?
? ? ? ? ? ? errorMsg = "文件名不是excel格式"; ?
? ? ? ? ? ? return false; ?
? ? ? ? } ?
? ? ? ? return true;
? }
? ??
? /**
? ?* 讀EXCEL文件,獲取客戶信息集合
? ?* @param fielName
? ?* @return
? ?*/
?
? public List<OilStation> getExcelInfo(String fileName,MultipartFile Mfile){
? ? ??
? ? ? //把spring文件上傳的MultipartFile轉換成CommonsMultipartFile類型
? ? ? ?CommonsMultipartFile cf= (CommonsMultipartFile)Mfile; //獲取本地存儲路徑
? ? ? ? File file = new ?File("D:\\fileupload");
? ? ? ?//創建一個目錄 (它的路徑名由當前 File 對象指定,包括任一必須的父路徑。)
? ? ? ?if (!file.exists()) file.mkdirs();
? ? ? ?//新建一個文件
? ? ? ?File file1 = new File("D:\\fileupload" + new Date().getTime() + ".xlsx");?
? ? ? ?//將上傳的文件寫入新建的文件中
? ? ? ?try {
? ? ? ? ? ?cf.getFileItem().write(file1);?
? ? ? ?} catch (Exception e) {
? ? ? ? ? ?e.printStackTrace();
? ? ? ?}
? ? ? ?
? ? ? ?//初始化客戶信息的集合 ? ?
? ? ? ?List<OilStation> oilStationList=new ArrayList<OilStation>();
? ? ? ?//初始化輸入流
? ? ? ?InputStream is = null; ?
? ? ? ?try{
? ? ? ? ? //驗證文件名是否合格
? ? ? ? ? if(!validateExcel(fileName)){
? ? ? ? ? ? ? return null;
? ? ? ? ? }
? ? ? ? ? //根據文件名判斷文件是2003版本還是2007版本
? ? ? ? ? boolean isExcel2003 = true;?
? ? ? ? ? if(WDWUtil.isExcel2007(fileName)){
? ? ? ? ? ? ? isExcel2003 = false; ?
? ? ? ? ? }
? ? ? ? ? //根據新建的文件實例化輸入流
? ? ? ? ? is = new FileInputStream(file1);
? ? ? ? ? //根據excel里面的內容讀取客戶信息
? ? ? ? ? oilStationList = (List<OilStation>) 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 oilStationList;
? }
? /**
? ?* 根據excel里面的內容讀取客戶信息
? ?* @param is 輸入流
? ?* @param isExcel2003 excel是2003還是2007版本
? ?* @return
? ?* @throws IOException
? ?*/
? public ?List<OilStation> getExcelInfo(InputStream is,boolean isExcel2003){
? ? ? ?List<OilStation> oilStationList=null;
? ? ? ?try{
? ? ? ? ? ?/** 根據版本選擇創建Workbook的方式 */
? ? ? ? ? ?Workbook wb = null;
? ? ? ? ? ?//當excel是2003時
? ? ? ? ? ?if(isExcel2003){
? ? ? ? ? ? ? ?wb = new HSSFWorkbook(is);?
? ? ? ? ? ?}
? ? ? ? ? ?else{//當excel是2007時
? ? ? ? ? ? ? ?wb = new XSSFWorkbook(is);?
? ? ? ? ? ?}
? ? ? ? ? ?//讀取Excel里面客戶的信息
? ? ? ? ? ?oilStationList=(List<OilStation>) readExcelValue(wb);
? ? ? ?}
? ? ? ?catch (IOException e) ?{ ?
? ? ? ? ? ?e.printStackTrace(); ?
? ? ? ?} ?
? ? ? ?return oilStationList;
? }
? /**
? ?* 讀取Excel里面客戶的信息
? ?* @param wb
? ?* @return
? ?*/
? private List<OilStation> readExcelValue(Workbook wb){?
? ? ? //得到第一個shell ?
? ? ? ?Sheet sheet=wb.getSheetAt(0);
? ? ? ?
? ? ? //得到Excel的行數
? ? ? ?this.totalRows=sheet.getPhysicalNumberOfRows();
? ? ? ?
? ? ? //得到Excel的列數(前提是有行數)
? ? ? ?if(totalRows>=1 && sheet.getRow(0) != null){
? ? ? ? ? ? this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells();
? ? ? ?}
? ? ? ?
? ? ? ?List<OilStation> oilStationList=new ArrayList<OilStation>();
? ? ? ?OilStation oilStation;
? ? ? //循環Excel行數,從第二行開始。標題不入庫
? ? ? ?for(int r=1;r<totalRows;r++){
? ? ? ? ? ?Row row = sheet.getRow(r);
? ? ? ? ? ?if (row == null) continue;
? ? ? ? ? ?oilStation = new OilStation();
? ? ? ? ? ?
? ? ? ? ? ?//循環Excel的列
? ? ? ? ? ?for(int c = 0; c <this.totalCells; c++){ ? ?
? ? ? ? ? ? ? ?Cell cell = row.getCell(c);
? ? ? ? ? ? ? ?//System.out.println("c======:"+c+"cell:"+cell);
? ? ? ? ? ? ? ?if(null != cell) {
? ? ? ? ? ? ? ? ? ?cell.setCellType(Cell.CELL_TYPE_STRING);
? ? ? ? ? ? ? ?}
? ? ? ? ? ? ?if(cell!=null && !cell.equals("")) {
? ? ? ? ? ? ? ? ? ?if(c==0){
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setStationCode(cell.getStringCellValue());//
? ? ? ? ? ? ? ? ? ?}else if(c==1){
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setProvince(cell.getStringCellValue());//
? ? ? ? ? ? ? ? ? ?}else if(c==2){
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setCity(cell.getStringCellValue());//
? ? ? ? ? ? ? ? ? ?}else if(c==3){
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setArea(cell.getStringCellValue());
? ? ? ? ? ? ? ? ? ?}else if(c==4){
? ? ? ? ? ? ? ? ? ? ? oilStation.setNotOilCode(cell.getStringCellValue());
? ? ? ? ? ? ? ? ? ?}else if(c==5){
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setName(cell.getStringCellValue());
? ? ? ? ? ? ? ? ? ?}else if(c==6){
? ? ? ? ? ? ? ? ? ? ? ?if(cell.getStringCellValue() != null && cell.getStringCellValue() != ""
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?&& !cell.getStringCellValue().equals("")) {
? ? ? ? ? ? ? ? ? ? ? ? ? ?oilStation.setStationType(Integer.valueOf(cell.getStringCellValue()));
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ?}else if(c==7){
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setAddress(cell.getStringCellValue());
? ? ? ? ? ? ? ? ? ?}else if(c==8){
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setTelephone(cell.getStringCellValue());
? ? ? ? ? ? ? ? ? ?}else if(c==9){//營業時間
? ? ? ? ? ? ? ? ? ? ? ?if(StringUtil.isNotEmpty(cell.getStringCellValue())) {
? ? ? ? ? ? ? ? ? ? ? ? ? ?oilStation.setBusinessHours(cell.getStringCellValue());
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ?}else if(c==10){//營業狀態
? ? ? ? ? ? ? ? ? ? ? ?String s = cell.getStringCellValue();
? ? ? ? ? ? ? ? ? ? ? ?if(s.contains("營業")) {
? ? ? ? ? ? ? ? ? ? ? ? ? ?oilStation.setWorkStatus(1);
? ? ? ? ? ? ? ? ? ? ? ?}else {
? ? ? ? ? ? ? ? ? ? ? ? ? ?oilStation.setWorkStatus(2);
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ?}else if(c==11){
? ? ? ? ? ? ? ? ? ? ? ?String s = cell.getStringCellValue();
? ? ? ? ? ? ? ? ? ? ? ?if(s.contains("是")) {
? ? ? ? ? ? ? ? ? ? ? ? ? ?oilStation.setAddMoney(1);
? ? ? ? ? ? ? ? ? ? ? ?}else {
? ? ? ? ? ? ? ? ? ? ? ? ? ?oilStation.setAddMoney(2);
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ?}else if(c==12){
? ? ? ? ? ? ? ? ? ? ? ?String s = cell.getStringCellValue();
? ? ? ? ? ? ? ? ? ? ? ?if(s.contains("是")) {
? ? ? ? ? ? ? ? ? ? ? ? ? ?oilStation.setMarket(1);
? ? ? ? ? ? ? ? ? ? ? ?}else {
? ? ? ? ? ? ? ? ? ? ? ? ? ?oilStation.setMarket(2);
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ?}else if(c==13){
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setLongitude(cell.getStringCellValue());
? ? ? ? ? ? ? ? ? ?}else if(c==14){
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setDimension(cell.getStringCellValue());
? ? ? ? ? ? ? ? ? ?}else if(c==15) {
? ? ? ? ? ? ? ? ? ? ? ?String s = cell.getStringCellValue();
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setSecond(Double.parseDouble("".equals(s.toString())?"0.00":s.toString()));
? ? ? ? ? ? ? ? ? ?}else if(c==16) {
? ? ? ? ? ? ? ? ? ? ? ?String s = cell.getStringCellValue();
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setFive(Double.parseDouble("".equals(s.toString())?"0.00":s.toString()));
? ? ? ? ? ? ? ? ? ?}else if(c==17) {
? ? ? ? ? ? ? ? ? ? ? ?String s = cell.getStringCellValue();
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setEight(Double.parseDouble("".equals(s.toString())?"0.00":s.toString()));
? ? ? ? ? ? ? ? ? ?}else if(c==18) {
? ? ? ? ? ? ? ? ? ? ? ?String s = cell.getStringCellValue();
? ? ? ? ? ? ? ? ? ? ? ?oilStation.setZero(Double.parseDouble("".equals(s.toString())?"0.00":s.toString()));
? ? ? ? ? ? ? ? ? ?}else if(c==19) {
? ? ? ? ? ? ? ? ? ? ? ?String s = cell.getStringCellValue();
? ? ? ? ? ? ? ? ? ? ? ?if(s.contains("是")) {
? ? ? ? ? ? ? ? ? ? ? ? ? ?oilStation.setCameraNumber("1");
? ? ? ? ? ? ? ? ? ? ? ?}else {
? ? ? ? ? ? ? ? ? ? ? ? ? ?oilStation.setCameraNumber("2");
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ?}else if(c==20) {
? ? ? ? ? ? ? ? ? ? ? ? ? ?oilStation.setRemark(cell.getStringCellValue());
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?
? ? ? ? ? ?}}
? ? ? ? ? ?//添加客戶
? ? ? ? ? ?oilStationList.add(oilStation);
? ? ? ?}
? ? ? ?return oilStationList;
? }
}
5.配置工具類ReadExcel引用的WDWUtil工具類,來判斷excel的版本:
public class WDWUtil {
? ? // @描述:是否是2003的excel,返回true是2003?
? ? public static boolean isExcel2003(String filePath) ?{ ?
? ? ? ? ?return filePath.matches("^.+\\.(?i)(xls)$"); ?
? ? ?} ?
? ?
? ? //@描述:是否是2007的excel,返回true是2007?
? ? public static boolean isExcel2007(String filePath) ?{ ?
? ? ? ? ?return filePath.matches("^.+\\.(?i)(xlsx)$"); ?
? ? ?} ?
}
6.配置讀取excel文件內容的接口,并添加到數據庫中:
@RequestMapping(value = "/batchAddOilStation", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
? ? ? public Map<String, Object> batchAddOilStation(@RequestParam(value = "filename") MultipartFile file,HttpServletRequest request) throws FileNotFoundException {
? ? ? Map<String, Object> map = new HashMap<>();
? ? ? try {
? ? ? ? ? ? ??
? ? ? ? ? ? ?String name = file.getOriginalFilename();
? ? ? ? ? ? ? ReadExcel read =new ReadExcel();
? ? ? ? ? ? ? List<OilStation> excelInfo = read.getExcelInfo(name, file);
? ? ? ? ? ? ? ?boolean flag = oilStationService.batchOwners(excelInfo);
? ? ? ? ? ? ? ?map.put("code", 200);
? ? ? ? ? ? ? ?map.put("msg", "");
? ? ? ? ? ? ? ?map.put("count", 1);
? ? ? ? ? ? ? ?map.put("data", flag);
? ? ? } catch (CodeException ce) {
? ? ? ? ? LOGGER.error(ce.getCode() + ":" + ce.getMessage());
? ? ? }
? ? ? return map;
? }
7.在jsp中需要配置:
<form>
? ??<div class="row cl">
?? ??? ??? ??? ??? ?<label class="form-label col-xs-4 col-sm-2">導入車輛模板:</label>
?? ??? ??? ??? ??? ?<div class="formControls col-xs-8 col-sm-10">
?? ??? ??? ??? ??? ??? ?<span class="btn-upload form-group">
?? ??? ??? ??? ??? ??? ? <input class="input-text upload-url" type="text" name="uploadfile"
?? ??? ??? ??? ??? ??? ??? ?id="uploadfile" readonly="" nullmsg="請添加附件!">
?? ??? ??? ??? ??? ??? ??? ?<a href=" " class="btn btn-primary radius upload-btn">
?? ??? ??? ??? ??? ??? ??? ?<i class="Hui-iconfont" style="width: 150px"></i> 瀏覽文件</a>?
?? ??? ??? ??? ??? ??? ??? ?<input type="file" multiple="" name="filename" id="filename" class="input-file">
?? ??? ??? ??? ??? ??? ?</span>
?? ??? ??? ??? ??? ??? ?<label class="btn btn-primary radius " οnclick="importExcel();" style="width: 150px">下載導入模板</label>
?? ??? ??? ??? ??? ?</div>
?? ??? ??? ??? ?</div>
</form>
8.在js中:
function importExcel(){?? ?
? ? ? ? ?? ?window.location.href = "/upload/uploadExcelModel/";?
? ? ? ? }?
submitHandler: function(form) {
?? ??? ??? ?var formData = new FormData($( "#form-add" )[0])
?? ??? ??? ?$.ajax({
?? ??? ??? ??? ?type: "post",
?? ??? ??? ??? ?url: contextPath + "/owners/add",
?? ??? ??? ??? ?data: formData,
?? ??? ??? ??? ?cache: false, ?
?? ??? ??? ? ? ?contentType: false, ?
?? ??? ??? ? ? ?processData: false,
?? ??? ??? ??? ?dataType: "json",
?? ??? ??? ??? ?success: function(data) {
?? ??? ??? ??? ??? ?},
?? ??? ??? ??? ?error: function(XMLHttpRequest, textStatus, errorThrown) {
?? ??? ??? ??? ??? ?//alert(errorThrown);
?? ??? ??? ??? ??? ?return false;
?? ??? ??? ??? ?}?
?? ??? ??? ?});
?? ??? ??? ?return false;
?? ??? ?}
總結
以上是生活随笔為你收集整理的java读取excel中的数据存到数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mybatis多条件查询
- 下一篇: 根据省市区查询对应权限下的数据