POI导入

一、pom 配置

<!-- poi,Excel导入导出 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.11</version>
        </dependency>

 

二、实体类

①Km

package sim.bistu.pojo;

import org.springframework.stereotype.Repository;

@Repository
public class Km {
    private String kmdm;
    private String kmmc;
    private String kmxz;
    private String yefx;

    public String getKmdm() {
        return kmdm;
    }

    public void setKmdm(String kmdm) {
        this.kmdm = kmdm;
    }

    public String getKmmc() {
        return kmmc;
    }

    public void setKmmc(String kmmc) {
        this.kmmc = kmmc;
    }

    public String getKmxz() {
        return kmxz;
    }

    public void setKmxz(String kmxz) {
        this.kmxz = kmxz;
    }

    public String getYefx() {
        return yefx;
    }

    public void setYefx(String yefx) {
        this.yefx = yefx;
    }

}


——————————————————————————————————————————————————

②ExcelBean

 

package sim.bistu.pojo;

import org.apache.poi.xssf.usermodel.XSSFCellStyle;

public class ExcelBean implements java.io.Serializable {  
    private String headTextName;//列头(标题)名  
    private String propertyName;//对应字段名  
    private Integer cols;//合并单元格数  
    private XSSFCellStyle cellStyle;  
      
    public ExcelBean(){  
          
    }  
    public ExcelBean(String headTextName, String propertyName){  
        this.headTextName = headTextName;  
        this.propertyName = propertyName;  
    }  
      
    public ExcelBean(String headTextName, String propertyName, Integer cols) {  
        super();  
        this.headTextName = headTextName;  
        this.propertyName = propertyName;  
        this.cols = cols;  
    }   
      
    public String getHeadTextName() {  
       return headTextName;  
   }  
 
   public void setHeadTextName(String headTextName) {  
       this.headTextName = headTextName;  
   }  
 
   public String getPropertyName() {  
       return propertyName;  
   }  
 
   public void setPropertyName(String propertyName) {  
       this.propertyName = propertyName;  
   }  
 
   public Integer getCols() {  
       return cols;  
   }  
 
   public void setCols(Integer cols) {  
       this.cols = cols;  
   }  
 
   public XSSFCellStyle getCellStyle() {  
       return cellStyle;  
   }  
 
   public void setCellStyle(XSSFCellStyle cellStyle) {  
       this.cellStyle = cellStyle;  
   }  

 

三、工具类ExcelUtils

package sim.bistu.util;

 

import java.io.IOException;  
import java.io.InputStream;  
import java.text.DecimalFormat;  
import java.text.SimpleDateFormat;  
import java.util.ArrayList;  
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;  
 
 
public class ExcelUtils {  
      
    private final static String excel2003L =".xls";    //2003- 版本的excel  
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel  
      
    /**
     * 描述:获取IO流中的数据,组装成List<List<Object>>对象
     * @param in,fileName
     * @return
     * @throws IOException  
     */  
    public  List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{  
        List<List<Object>> list = null;  
          
        //创建Excel工作薄  
        Workbook work = this.getWorkbook(in,fileName);  
        if(null == work){  
            throw new Exception("创建Excel工作薄为空!");  
        }  
        Sheet sheet = null;  
        Row row = null;  
        Cell cell = null;  
          
        list = new ArrayList<List<Object>>();  
        //遍历Excel中所有的sheet  
        for (int i = 0; i < work.getNumberOfSheets(); i++) {  
            sheet = work.getSheetAt(i);  
            if(sheet==null){continue;}  
              
            //遍历当前sheet中的所有行  
            for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum(); j++) {  
                row = sheet.getRow(j);  
                if(row==null||row.getFirstCellNum()==j){continue;}  
                  
                //遍历所有的列  
                List<Object> li = new ArrayList<Object>();  
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {  
                    cell = row.getCell(y);  
                    li.add(this.getCellValue(cell));  
                }  
                list.add(li);  
            }  
        }  
        //work.close();  
        return list;  
    }  
      
    /**
     * 描述:根据文件后缀,自适应上传文件的版本  
     * @param inStr,fileName
     * @return
     * @throws Exception
     */  
    public  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{  
        Workbook wb = null;  
        String fileType = fileName.substring(fileName.lastIndexOf("."));  
        if(excel2003L.equals(fileType)){  
            wb = new HSSFWorkbook(inStr);  //2003-  
        }else if(excel2007U.equals(fileType)){  
            wb = new XSSFWorkbook(inStr);  //2007+  
        }else{  
            throw new Exception("解析的文件格式有误!");  
        }  
        return wb;  
    }  
 
    /**
     * 描述:对表格中数值进行格式化
     * @param cell
     * @return
     */  
    public  Object getCellValue(Cell cell){  
        Object value = null;  
        DecimalFormat df = new DecimalFormat("0");  //格式化number String字符  
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化  
        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字  
          
        switch (cell.getCellType()) {  
        case Cell.CELL_TYPE_STRING:  
            value = cell.getRichStringCellValue().getString();  
            break;  
        case Cell.CELL_TYPE_NUMERIC:  
            if("General".equals(cell.getCellStyle().getDataFormatString())){  
                value = df.format(cell.getNumericCellValue());  
            }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){  
                value = sdf.format(cell.getDateCellValue());  
            }else{  
                value = df2.format(cell.getNumericCellValue());  
            }  
            break;  
        case Cell.CELL_TYPE_BOOLEAN:  
            value = cell.getBooleanCellValue();  
            break;  
        case Cell.CELL_TYPE_BLANK:  
            value = "";  
            break;  
        default:  
            break;  
        }  
        return value;  
    }  
      
 
}  

 

四、ServiceImpl类:KmServiceImpl

package sim.bistu.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import sim.bistu.mapper.KmDao;
import sim.bistu.mapper.UserDao;
import sim.bistu.pojo.Km;
import sim.bistu.pojo.User;
import sim.bistu.util.ExcelUtils;

@Service
//@Transactional
public class KmServiceImpl implements KmService {

    @Autowired
    private  KmDao KmDao;
   

    
    public String ajaxUploadExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
        //MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;

            MultipartFile file = multipartRequest.getFile("file");

            System.out.println("得到数据文件");
            if(file.isEmpty()){
                try {
                    throw new Exception("文件不存在!");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            InputStream in =null;
            try {
                in = file.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("加载流");
            List<List<Object>> listob = null;
            try {
                System.out.println("加载流");
                listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
            } catch (Exception e) {
                e.printStackTrace();
            }

            //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出
            for (int i = 0; i < listob.size(); i++) {
                List<Object> lo = listob.get(i);
                System.out.println("遍历" + listob.get(i));
                Km vo = new Km();
                Km j = null;

                try {
                    //j = studentmapper.selectByPrimaryKey(Long.valueOf());
                    j = KmDao.FindKmByKmdm(String.valueOf(lo.get(0)));
                } catch (NumberFormatException e) {
                    // TODO Auto-generated catch block
                    System.out.println("没有新增");
                }

                
               /* vo.setKmdm(String.valueOf(lo.get(0)));
                vo.setKmmc(String.valueOf(lo.get(1)));
                vo.setKmxz(String.valueOf(lo.get(2)));
                vo.setYefx(String.valueOf(lo.get(3)));*/
                
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("kmdm", String.valueOf(lo.get(0)));
                map.put("kmmc", String.valueOf(lo.get(1)));
                map.put("kmxz", String.valueOf(lo.get(2)));
                map.put("yefx", String.valueOf(lo.get(3)));
                if(j == null)
                {
                    KmDao.insertKm(map);
                }
                else
                {
                    //studentmapper.updateByPrimaryKey(vo);
                     System.out.println("科目已存在!!!");
                }
            }
            return "success";
        }
}

 

五、持久化层

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="sim.bistu.mapper.KmDao">
  
    <select id="FindKmByKmdm" resultType="Km" parameterType="String">
        select * from km where kmdm = #{kmdm}
    </select>

    <!-- 插入科目 -->
    <insert id="insertKm" parameterType="Map">
        insert into km (kmdm, kmmc, kmxz,yefx)
        values (#{kmdm}, #{kmmc}, #{kmxz},
        #{yefx})
    </insert>
</mapper>

 

 

六、Controller类

package sim.bistu.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import sim.bistu.pojo.Km;
import sim.bistu.service.KmService;

@Controller
@RequestMapping("/KmController")
public class KmController {
    @Autowired
    KmService KmService;

    @ResponseBody
    @RequestMapping(value="ajaxUpload",method={RequestMethod.GET,RequestMethod.POST})
    public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
        System.out.println("这是请求");
         return KmService.ajaxUploadExcel(request, response);
    }
    
}

 

 

七、jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>


    <form
        action="${pageContext.request.contextPath}/KmController/ajaxUpload.do"
        method="post" enctype="multipart/form-data">
        请选择Excel:<input type="file" name="file"> <input type="submit"
            name="上传">
    </form>

</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值