SSM实现Excel的导入导出功能

需要的jar包

    
		 org.apache.poi
		 poi
		 3.14
	 
	 
		 org.apache.poi
		 poi-ooxml-schemas
		 3.14
	 
	 
		 org.apache.poi
		 poi-ooxml
		 3.14
	 
	 
		 org.apache.httpcomponents
		 httpclient
		 4.5.2
	 

工具类

public class ExcelUtil {

    private final static String excel2003L =".xls";    //2003- 版本的excel
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel

    /**
     * 描述:获取IO流中的数据,组装成List>对象
     * @param in,fileName
     * @return
     * @throws
     */
    public  List> getBankListByExcel(InputStream in,String fileName) throws Exception{
        List> 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>();
        //遍历Excel中所有的sheet
        // 将最大的列数记录下来
        int lastCellNum = 0;
        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){continue;}

                //遍历所有的列
                List li = new ArrayList();
                // 比较当前行的列数跟表的最大的列数
                if (j == sheet.getFirstRowNum()) {
                    // 将第一行的列数设为最大
                    lastCellNum = row.getLastCellNum();
                }else {
                    lastCellNum = lastCellNum > row.getLastCellNum() ? lastCellNum : row.getLastCellNum();
                }
                for (int y = row.getFirstCellNum(); y < lastCellNum; y++) {
                    cell = row.getCell(y);
                    li.add(this.getValue(cell));
                }
                System.out.println(list.toString());
                list.add(li);
            }
        }

        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
     */
    //解决excel类型问题,获得数值
    public  String getValue(Cell cell) {
        String value = "";
        if(null==cell){
            return value;
        }
        switch (cell.getCellType()) {
            //数值型
            case Cell.CELL_TYPE_NUMERIC:
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    //如果是date类型则 ,获取该cell的date值
                    Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
                    // 根据自己的实际情况,excel表中的时间格式是yyyy-MM-dd HH:mm:ss还是yyyy-MM-dd,或者其他类型
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    // 由于方法的返回值类型为String,这里将Date类型转为String,便于统一返回数据
                    value = format.format(date);;
                }else {// 纯数字
                    BigDecimal big=new BigDecimal(cell.getNumericCellValue());
                    value = big.toString();
                    //解决1234.0  去掉后面的.0
                    if(null!=value&&!"".equals(value.trim())){
                        String[] item = value.split("[.]");
                        if(1 clazz,
            List> objs,
            Map> map,
            String sheetName) throws Exception{
        //创建新的工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建工作表
        XSSFSheet sheet = workbook.createSheet(sheetName);
        //设置excel的字体样式以及标题与内容的创建
        createFont(workbook);//字体样式
        createTableHeader(sheet,map);//创建标题
        createTableRows(sheet,map,objs,clazz);//创建内容
        System.out.println(workbook);
        return workbook;
    }

    private static XSSFCellStyle fontStyle;
    private static XSSFCellStyle fontStyle2;
    private static void createFont(XSSFWorkbook workbook) {
        //表头
        fontStyle = workbook.createCellStyle();
        XSSFFont font1 = workbook.createFont();
        font1.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        font1.setFontName("黑体");
        font1.setFontHeightInPoints((short) 12);//字体大小
        fontStyle.setFont(font1);
        fontStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);//下边框
        fontStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);//左边框
        fontStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);//右边框
        fontStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);//右边框
        fontStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);//居中
        //内容
        fontStyle2 = workbook.createCellStyle();
        XSSFFont font2 = workbook.createFont();
        font2.setFontName("宋体");
        font2.setFontHeightInPoints((short)10);
        fontStyle2.setFont(font2);
        fontStyle2.setBorderBottom(XSSFCellStyle.BORDER_THIN);//下边框
        fontStyle2.setBorderLeft(XSSFCellStyle.BORDER_THIN);//左边框
        fontStyle2.setBorderTop(XSSFCellStyle.BORDER_THIN);//右边框
        fontStyle2.setBorderRight(XSSFCellStyle.BORDER_THIN);//右边框
        fontStyle2.setAlignment(XSSFCellStyle.ALIGN_CENTER);//居中
    }

    /**
     * 根据ExcelMapping 生成列头(多行列头)
     * @param sheet 工作簿
     * @param map 每行每个单元格对应的列头信息
     */
    private static void createTableHeader(
            XSSFSheet sheet,
            Map> map) {
        int startIndex = 0;//cell起始位置
        int endIndex = 0;//cell终止位置
        for(Map.Entry> entry: map.entrySet()){
            XSSFRow row = sheet.createRow(entry.getKey()); //创建行
            List excels = entry.getValue();
            for(int x=0;x1){
                    if(x==0){
                        endIndex += excels.get(x).getCols()-1;
                        //合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
                        sheet.addMergedRegion(new CellRangeAddress(0, 0, startIndex, endIndex));
                        startIndex += excels.get(x).getCols();
                    }else{
                        endIndex += excels.get(x).getCols();
                        sheet.addMergedRegion(new CellRangeAddress(0, 0, startIndex, endIndex));
                        startIndex += excels.get(x).getCols();
                    }
                    XSSFCell cell = row.createCell(startIndex-excels.get(x).getCols());
                    //设置内容
                    cell.setCellValue(excels.get(x).getHeadTextName());
                    if(excels.get(x).getCellStyle() != null){
                        //设置格式
                        cell.setCellStyle(excels.get(x).getCellStyle());
                    }
                    cell.setCellStyle(fontStyle);
                }else{
                    XSSFCell cell = row.createCell(x);
                    //设置内容
                    cell.setCellValue(excels.get(x).getHeadTextName());
                    if(excels.get(x).getCellStyle() != null){
                        //设置格式
                        cell.setCellStyle(excels.get(x).getCellStyle());
                    }
                    cell.setCellStyle(fontStyle);
                }
            }
        }
    }

    /**
     * 为excel表中循环添加数据
     * @param sheet
     * @param map  字段名
     * @param objs	查询的数据
     * @param clazz 无用
     */
    private static void createTableRows(
            XSSFSheet sheet,
            Map> map,
            List> objs,
            Class clazz)
            throws Exception{
        int rowindex = map.size();
        int maxkey = 0;
        List ems = new ArrayList();
        for(Map.Entry> entry : map.entrySet()){
            if(entry.getKey() > maxkey){
                maxkey = entry.getKey();
            }
        }
        ems = map.get(maxkey);
        List widths = new ArrayList(ems.size());
        for(Map obj : objs){
            XSSFRow row = sheet.createRow(rowindex);
            for(int i=0;i10000?10000+300:width+300;
            sheet.setColumnWidth(index, width);
        }
    }


} 
   
  

service接口

public interface ExcelService {

    /**
     * 导入excel
     * @param file  excel文件
     * @return  0表示失败,1表示成功
     * @throws Exception
     */
    String ajaxUploadExcel(MultipartFile file) throws Exception;

    /**
     * 导入excel
     * @return
     * @throws Exception
     */
    XSSFWorkbook exportExcelInfo() throws Exception;

}

 service实现类

@Service
public class ExcelServiceImpl implements ExcelService {

    @Autowired
    private UserDao dao;
    @Autowired
    private UserService service;


    protected static Logger logger = LoggerFactory.getLogger(ExcelServiceImpl.class);

    public String ajaxUploadExcel(MultipartFile file) throws Exception {
        if(file.isEmpty()){
            try {
                throw new Exception("文件不存在!");
            } catch (Exception e) {
                logger.debug(e.getMessage());
            }
        }
        InputStream in =null;
        try {
            in = file.getInputStream();
        } catch (IOException e) {
            logger.debug(e.getMessage());
        }

        List> listob = null;
        try {
            //将文件中的数据转换成一个list集合
            listob = new ExcelUtil().getBankListByExcel(in,file.getOriginalFilename());
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }


        //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出
        for (int i = 0; i < listob.size(); i++) {
            User userExcel = new User();
            /*
                设置值之前可以进行验证哪些字段是不能再添加的
             */
            if (StringUtils.isEmpty(String.valueOf(listob.get(i).get(1))) || StringUtils.isEmpty(String.valueOf(listob.get(i).get(0))) || StringUtils.isEmpty(String.valueOf(listob.get(i).get(3)))){
                throw new Exception("基本信息不能为空");
            }
            if (service.validateUseridcard(String.valueOf(listob.get(i).get(1)))){
                throw new Exception("身份证号码不能一致");
            }
            userExcel.setName(String.valueOf(listob.get(i).get(0)));     // 表格的第一列   注意数据格式需要对应实体类属性
            userExcel.setIdcard(String.valueOf(listob.get(i).get(1)));   // 表格的第二列
            userExcel.setMobiile(java.lang.String.valueOf(listob.get(i).get(2)));   // 表格的第三列
            userExcel.setAddress(String.valueOf(listob.get(i).get(3)));   // 表格的第四列
            userExcel.setAge(String.valueOf(listob.get(i).get(4)));       // 表格的第五列
            //由于数据库中此字段是datetime,所以要将字符串时间格式:yyyy-MM-dd HH:mm,转为Date类型
            if (!StringUtils.isEmpty(listob.get(i).get(5))) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                userExcel.setBirtday(sdf.parse(String.valueOf(listob.get(i).get(5)))); // 表格的第六列
            }else {
                userExcel.setBirtday(new Date());
            }
            logger.info("读取的对象是:"+userExcel);
            //进行数据保存
            dao.saveUser(userExcel);
        }
        logger.info("文件导入成功!");
        return "1";
    }

    public XSSFWorkbook exportExcelInfo() throws Exception {
        List> list = dao.getUsermap();
        List excel = new ArrayList();
        Map> map = new LinkedHashMap>();
        /*
            设置标题栏(根据数据库的列名进行设置)
            如果发现某一列没有内容可以自行debug(ExcelUtil.createTableRows)这个方法循环添加值那里的if是否进去然后设置为空了
            多半是map的key没有写对
         */
        excel.add(new ExcelBean("主键","userid",0));
        excel.add(new ExcelBean("用户名","NAME",0));
        excel.add(new ExcelBean("身份证号码","idcard", 0));
        excel.add(new ExcelBean("手机号码","mobiile",0));
        excel.add(new ExcelBean("地址","address",0));
        excel.add(new ExcelBean("出生日期","birtday",0));
        excel.add(new ExcelBean("年龄","age",0));
        map.put(0,excel);
        String sheetName = "用户信息表";
        //调用ExcelUtil方法
        XSSFWorkbook xssfWorkbook = ExcelUtil.createExcelFile(User.class, list, map, sheetName);
        logger.info("文件导出成功");
        return xssfWorkbook;
    }

}

 实体类

public class ExcelBean implements Serializable {

    private String headTextName; //列头(标题)名
    private String propertyName; //对应字段名
    private Integer cols; //合并单元格数
    private XSSFCellStyle cellStyle;

    public ExcelBean(String headTextName, String propertyName, Integer cols, XSSFCellStyle cellStyle) {
        this.headTextName = headTextName;
        this.propertyName = propertyName;
        this.cols = cols;
        this.cellStyle = cellStyle;
    }

    public ExcelBean(String headTextName, String propertyName, Integer cols) {
        this.headTextName = headTextName;
        this.propertyName = propertyName;
        this.cols = cols;
    }

    public ExcelBean() {
    }

    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;
    }
}

@RequestMapping(value="ajaxUpload", produces = "application/text; charset=utf-8",method = RequestMethod.POST)
	@ResponseBody
	public String UploadExcel(@RequestParam(value = "upfile",required = false) MultipartFile file){
		String msg = null;
		try {
			msg = excelService.ajaxUploadExcel(file);
			return msg;
		} catch (Exception e) {
			System.err.println(e.getMessage());
			logger.debug(e.getMessage());
		}
		return "0";
	}

	@RequestMapping(value = "downloadExcel",method = RequestMethod.POST)
	public void downloadExcel(HttpServletRequest request,HttpServletResponse response){
		//导出Excel对象
		XSSFWorkbook workbook = null;
		OutputStream output = null;
		BufferedOutputStream bufferedOutput = null;
		try {
			response.reset(); //清除buffer缓存
			//Map map=new HashMap();
			// 指定下载的文件名
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.setHeader("Content-Disposition","attachment;filename="+new String("用户表.xlsx".getBytes(),"iso-8859-1"));
			//将查到的数据用XSSFWorkbook保存并创建一个流
			workbook = excelService.exportExcelInfo();
			output = response.getOutputStream();
			bufferedOutput = new BufferedOutputStream(output);
			bufferedOutput.flush();
			//最后通过流写进去
			workbook.write(bufferedOutput);
		} catch (Exception e) {
			System.err.println(e.getMessage());
			logger.debug(e.getMessage());
		}finally {
			try {
				bufferedOutput.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

html

jquery

 $("#importExcel").on("click",function (){
                    var formData = new FormData()
                    //检验导入的文件是否为Excel文件
                    var uploadFile = $('#upfile').val()
                    formData.append("upfile",$("#upfile")[0].files[0])
                    formData.append("name",uploadFile)
                    if(uploadFile == null || uploadFile == ''){
                        alert("请选择要上传的Excel文件")
                        return false;
                    }else{
                        var fileExtend = uploadFile.substring(uploadFile.lastIndexOf('.')).toLowerCase();
                        if(fileExtend == '.xls' || fileExtend == '.xlsx'){
                            $.ajax({
                                url:"ajaxUpload",
                                type:"POST",
                                data:formData,
                                processData:false,
                                contentType:false,
                                success:function (data) {
                                    if (data == '1'){
                                        alert("导入成功")
                                    }else{
                                        alert("导入失败,日志有错误信息")
                                    }
                                }

                            })
                            return true
                        }else{
                            alert("文件格式需为.xls格式或者.xlsx格式");
                            return false
                        }
                    }
            })

            $("#downloadExcel").on("click",function (){
                //弹出对话框
                var result = confirm("是否导出Excel?")
                if (result) {
                    $.post('downloadExcel')//直接发出请求不需要参数啥的
                }
            })

你可能感兴趣的:(java,eureka,spring)