采用spring mvc 和mybatis框架 将excel数据导入到Mysql数据库

来源:互联网 发布:未知网络错误 编辑:程序博客网 时间:2024/06/06 05:43

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包


基本修饰这样了

1 0
原创粉丝点击