1. 程式人生 > >採用spring mvc 和mybatis框架 將excel資料匯入到Mysql資料庫

採用spring mvc 和mybatis框架 將excel資料匯入到Mysql資料庫

1.jsp部分:

<form action = "price/excelUpload" method = "post" enctype="multipart/form-data">
                  <input class="fileFrom" type="file" name="filename" ><br/>
                  <input class="formSubmit" type="submit" value="立即新增" name="">

 </form>

2.Controller部分:

@RequestMapping("/excelUpload")
public String excelUpload(@RequestParam(value="filename") MultipartFile file,HttpServletRequest request,HttpServletResponse response){
if(file==null) return null;
    //獲取檔名
    String name=file.getOriginalFilename();
    //進一步判斷檔案是否為空(即判斷其大小是否為0或其名稱是否為null)
    long size=file.getSize();
    if(name==null || ("").equals(name) && size==0) return null;
    
    //批量匯入。引數:檔名,檔案。
    boolean b = ps.excelUpload(name, file);
    if(b){
         String Msg ="批量匯入EXCEL成功!";
         request.getSession().setAttribute("msg",Msg);    
    }else{
         String Msg ="批量匯入EXCEL失敗!";
         request.getSession().setAttribute("msg",Msg);
    }
   
return "***";
}

3.serviceImpl部分

@Override
public boolean excelUpload(String name, MultipartFile file) {
boolean b = false;
       //建立處理EXCEL
       ReadExcelMaterial readExcel=new ReadExcelMaterial();
       //解析excel,獲取客戶資訊集合。
       List<Price> priceList= readExcel.getExcelInfo(name, file);


       if(materialList != null){
           b = true;
       }
       
       //迭代新增客戶資訊(注:實際上這裡也可以直接將customerList集合作為引數,在Mybatis的相應對映檔案中使用foreach標籤進行批量新增。)
       for(Price price:priceList){
           pm.addPrice(price);
       }
       return b;
}

4.util


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;






import cn.jane.service.PriceService;
import cn.jane.entity.Price;


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; }  
    
  /**
   * 驗證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<Price> 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<Price> priceList=new ArrayList<Price>();
       //初始化輸入流
       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裡面的內容讀取客戶資訊
          priceList = 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 priceList;
  }
  /**
   * 根據excel裡面的內容讀取客戶資訊
   * @param is 輸入流
   * @param isExcel2003 excel是2003還是2007版本
   * @return
   * @throws IOException
   */
  public  List<Price> getExcelInfo(InputStream is,boolean isExcel2003){
       List<Price> priceList = null;
       try{
           /** 根據版本選擇建立Workbook的方式 */
           Workbook wb = null;
           //當excel是2003時
           if(isExcel2003){
               wb = new HSSFWorkbook(is); 
           }
           else{//當excel是2007時
               //wb = new XSSFWorkbook(is); 
          wb = new XSSFWorkbook(is);
           }
           //讀取Excel裡面客戶的資訊
           priceList=readExcelValue(wb);
       }
       catch (IOException e)  {  
           e.printStackTrace();  
       }  
       return priceList;
  }
  /**
   * @param wb
   * @return
   */
  private List<Price> readExcelValue(Workbook wb){ 
      //得到第一個shell  
 System.out.println("luhan***********************************");
       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<Price> priceList=new ArrayList<Price>();
       Price price;            
      //迴圈Excel行數,從第二行開始。標題不入庫
       for(int r=1;r<totalRows;r++){
           Row row = sheet.getRow(r);
           if (row == null) continue;
           price = new Price();
           
           //迴圈Excel的列
           for(int c = 0; c <this.totalCells; c++){    
               Cell cell = row.getCell(c);
              
        
               if (null != cell){
                   if(c==0){
//                  CELL.SETCELLTYPE(CELL.CELL_TYPE_STRING);
                  cell.setCellType(Cell.CELL_TYPE_STRING);
                  System.out.println("luhan"+cell.getStringCellValue());
                  price.setMaterial_num(cell.getStringCellValue());
                   }else if(c==1){
                  
                  System.out.println("luhan"+cell.getStringCellValue());
                  price.setMaterial_name(cell.getStringCellValue());
               
                   }else if(c==2){
                  price.setPrice_info(cell.getNumericCellValue());
                  
                   }else if(c==3){
                  price.setPrice_tech(cell.getNumericCellValue());
                   }else if(c==4){
                  price.setPrice_bid(cell.getNumericCellValue());
                   }else if(c==5){
                  price.setPrice_contra(cell.getNumericCellValue());
                   }else if(c==6){
                  price.setPrice_account(cell.getNumericCellValue());
                   }else if(c==7){
                  price.setPrice_market(cell.getNumericCellValue());
                   }else if(c==8){
                 Date date = cell.getDateCellValue();
                 SimpleDateFormat format = new SimpleDateFormat();
                 String str = format.format(date);
                  price.setPrice_time(str);
                   }
               }
           }
           //新增
           priceList.add(price);
       }
       return priceList;
  }

//這個工具類裡面後面set實體類的屬性時有 可能出現:不能將一個單元格數字轉化成字串等異常,這時需要通過 cell.setCellType(Cell.CELL_TYPE_STRING);來將其轉化,日期也是類似。這裡要特別注意,當時我就是被這個問題折磨了好久。
第二個工具類,判斷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)$");  
     }  
 
}

sql語句求不用寫了,就是一般的insert 實體類

最後還要注意的是xml需要新增



 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
 </bean>

相應的jar包


基本修飾這樣了