java實現的Excel批量導入

  導入Mavenjava

1     <dependency>
2             <groupId>org.jeecg</groupId>
3             <artifactId>easypoi-base</artifactId>
4             <version>2.3.1</version>
5         </dependency>

  本人的Excle表sql

  

  

 

  定義一個實體類用於接收解析Excle裏的數據app

package ********.entity;

import java.io.Serializable;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
 * 批量導入的實體類
 * @author 
 *
 */
@Data
@NoArgsConstructor    
@AllArgsConstructor
public class TblFixChange implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    /**手機號**/
    private String preferentialPhone;
    /**車牌號**/
    private String preferentialCarNumber;
    
    /**-- 優惠分組的id --**/
    private String groupingId;

    /**-- 建立時間 --**/
    private String createTime;

    /**-- 修改時間 --**/
    private String modifyTime;


}

 

 

  Controlleride

    //導入
    @RequestMapping(value = "/im/activity/upload", method = RequestMethod.POST)
    public Map<String, Object> importExcel(@RequestParam("file") MultipartFile file) throws IOException, Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = groupConfigService.importExcel(file);
            
        } catch (Exception e) {
            map.put("status",-1);
            map.put("data", "導入異常");
        }
        return map;
        
    }

  serviceImplspa

/**
     * 批量導入(批量添加)
     */

      private static final String XLS = "xls";
      private static final String XLSK = "xlsx";  //定義全局的常量值code


    @SuppressWarnings("resource")
    public Map<String, Object> importExcel(MultipartFile file) throws Exception {
        List<TblFixChange> list = new ArrayList<TblFixChange>();
        Map<String, Object> rsultMap = new HashMap<String, Object>();
      
        
        Workbook workbook = null;
        String fileName = myFile.getOriginalFilename();
        if(fileName.endsWith(XLS)) {
            //2003
            try {
                workbook = new HSSFWorkbook(file.getInputStream());
            } catch (Exception e) {
                e.printStackTrace( );
            }
            
        }else if(fileName.endsWith(XLSK)) {
            try {
                //2007
                workbook = new XSSFWorkbook(file.getInputStream());
            } catch (Exception e) {
                e.printStackTrace( );
            }
        }else {
            throw new Exception("文件不是Excel文件");
        }
        Sheet sheet = workbook.getSheet("Sheet1");
        int rows = sheet.getLastRowNum();//指定行數。一共多少+
        if(rows==0) {
            throw new Exception("請填寫行數");
        }
        
        for (int i = 1; i < rows+1; i++) {
            //讀取左上端單元格
            Row row = sheet.getRow(i);
            //行不爲空
            if(row != null) {
                //讀取cell
                TblFixChange tblFixChange = new TblFixChange();
                //手機號
                String phone = getCellValue(row.getCell(0));
                tblFixChange.setPreferentialPhone(phone);
                //車牌號
                String catNumber = getCellValue(row.getCell(1));
                tblFixChange.setPreferentialCarNumber(catNumber);
                //組的id
                String groupId = getCellValue(row.getCell(2));
             
                tblFixChange.setGroupingId(groupId);

          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          String time = sdf.format(new Date());
          tblFixChange.setCreateTime(time);
          tblFixChange.setModifyTime(time);orm

                list.add(tblFixChange);  //把實數據放入集合裏
            }
        }
        try {
            groupConfigDao.addBatchMembers(list);  //批量添加 (執行sql語句批量增長)
            rsultMap.put("status", 1);
            rsultMap.put("data", "導入數據成功");
        } catch (Exception e) {
            rsultMap.put("status", -1);
            rsultMap.put("data", "導入數據異常");
        }
        
        return rsultMap;
    }
//獲取Cell內容
    private String getCellValue(Cell cell) {
        String value = "";
        if(cell != null) {
            //如下是判斷數據的類型
            switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_NUMERIC://數字
                value = cell.getNumericCellValue() + "";
                if(HSSFDateUtil.isCellDateFormatted(cell)) {
                    Date date = cell.getDateCellValue();
                    if(date != null) {
                        value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                    }else {
                        value = "";
                    }
                }else {
                    value = new DecimalFormat("0").format(cell.getNumericCellValue());
                }
                break;
            case HSSFCell.CELL_TYPE_STRING: //字符串
                value = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN: //boolean
                value = cell.getBooleanCellValue() + "";
                break;
            case HSSFCell.CELL_TYPE_FORMULA: //公式
                value = cell.getCellFormula() + "";
                break;
            case HSSFCell.CELL_TYPE_BLANK: //空值
                value = "";
                break;
            case HSSFCell.CELL_TYPE_ERROR: //故障
                value = "非法字符";
                break;
            default:
                value = "未知類型";
                break;
            }
        }
        return value.trim();
    }
    

 

sql語句的批量增長(本人的id是自增加的)blog

<insert id="addBatchMembers"  parameterType="java.util.List">
    
        INSERT INTO activity_prefere (
        <trim suffix="" suffixOverrides=",">
             preferential_car_number ,
             grouping_id ,
             create_time ,
             modify_time ,
             preferential_phone 
        </trim>
        ) VALUES 
        <foreach collection="list" item="item" index="index" separator=",">
            (
                #{item.preferentialCarNumber} ,
                #{item.groupingId} ,
                #{item.createTime} ,
                #{item.modifyTime} ,
                #{item.preferentialPhone} 
            )
           </foreach>
    </insert> 
相關文章
相關標籤/搜索