1.导入jar包

<!-- poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.11</version>
        </dependency>

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-examples</artifactId>
            <version>3.17</version>
        </dependency>

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-excelant</artifactId>
            <version>3.17</version>
        </dependency>

2.配置下载模板

在controller中写下载模板接口:

@Controller
@RequestMapping(value = "/excelModel")
public class PoiExpExcel {
    
    @RequestMapping(value = "/importExcelModel", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelAndView exportExcel()throws Exception{ 
        ModelAndView mv = new ModelAndView();  
        Map<String,Object> dataMap = new HashMap<String,Object>();  
        List<String> titles = new ArrayList<String>();  
        titles.add("油站编号");  
        titles.add("所属省份");  
        titles.add("所属城市");
        titles.add("所属片区");  
        titles.add("非油品编码");  
        titles.add("油站名"); 
        titles.add("油站类型"); 
        titles.add("具体位置"); 
        titles.add("电话(含区号)"); 
        titles.add("营业时间"); 
        titles.add("营业/关停"); 
        titles.add("是否有充值业务"); 
        titles.add("是否有便利店"); 
        titles.add("经度"); 
        titles.add("纬度"); 
        titles.add("92#"); 
        titles.add("95#"); 
        titles.add("98#"); 
        titles.add("0#"); 
        dataMap.put("titles", titles);  
        ObjectExcelView erv = new ObjectExcelView();  
        mv = new ModelAndView(erv,dataMap);  
           return mv;    }

}

在接口中使用了工具类ObjectExcelView:

public class ObjectExcelView extends AbstractExcelView{
    
    @Override  
    protected void buildExcelDocument(Map<String, Object> model,  
            HSSFWorkbook workbook, HttpServletRequest request,  
            HttpServletResponse response) throws Exception {  
        // TODO Auto-generated method stub  
        Date date = new Date();
        String filename = Tools.date2Str(date, "yyyyMMddHHmmss");
        HSSFSheet sheet;  
        HSSFCell cell;  
        response.setContentType("application/octet-stream");  
        response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls");  
        sheet = workbook.createSheet("sheet1"); 
        
        List<String> titles = (List<String>) model.get("titles");  
        int len = titles.size();  
        HSSFCellStyle headerStyle = workbook.createCellStyle(); //标题样式  
        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
        headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
        HSSFFont headerFont = workbook.createFont();    //标题字体  
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
        headerFont.setFontHeightInPoints((short)11);  
        headerStyle.setFont(headerFont);  
        short width = 20,height=25*20;  
        sheet.setDefaultColumnWidth(width);  
        HSSFRow row=sheet.createRow(0);
        for(int i=0; i<len; i++){ //设置标题  
            String title = titles.get(i);
                if(title.equals("模板使用教程")) {
                HSSFCell createCell = row.createCell(i);
                //createCell.setCellValue("模板使用说明: 在油站类型列  1-中石油,2-中石化,3-其它加油站"+"\n");
                createCell.setCellValue("模板使用说明: 在油站类型列  1-中石油,2-中石化,3-其它加油站");
                HSSFCellStyle style=workbook.createCellStyle();
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
                style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
                style.setWrapText(true);//自动换行
                style.setIndention((short)3);//缩进
                HSSFFont font = workbook.createFont();
                font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

font.setColor(Font.COLOR_RED);//设置字体颜色
                style.setFont(font);
                createCell.setCellStyle(style);
                //设置合并单元格,第一个参数:起始行号;第二个参数:结束行号;第三个参数:起始列号;第四个参数:结束列号;
                CellRangeAddress region=new CellRangeAddress(0, 3, i, i+1);
                sheet.addMergedRegion(region);
                 
            }else {
                cell = getCell(sheet, 0, i);  
                cell.setCellStyle(headerStyle);  
                setText(cell,title);
            }
         /*if(title.equals("车辆类型")) {
             CellRangeAddressList regions = new CellRangeAddressList(1, 65535,i, i);
             DVConstraint constraint =DVConstraint.createExplicitListConstraint(new String[] { "轿车","货运", "客车","工程车","卡车","SUV","MVP","油品运输车","燃气运输车"});
             HSSFDataValidation dataValidate = new HSSFDataValidation(regions,constraint);
              sheet.addValidationData(dataValidate);    
             }
         if(title.equals("油品类型")) {
             CellRangeAddressList regions = new CellRangeAddressList(1, 65535,i, i);
             DVConstraint constraint =DVConstraint.createExplicitListConstraint(new String[] {"92#", "95#","98#", "5#","0#","-10#","-20#"});
             HSSFDataValidation dataValidate = new HSSFDataValidation(regions,constraint);
              sheet.addValidationData(dataValidate);    
             }
         if(title.equals("车辆等级")) {
             CellRangeAddressList regions = new CellRangeAddressList(1, 65535,i, i);
             DVConstraint constraint =DVConstraint.createExplicitListConstraint(new String[] { "黑卡","钻石卡", "白金卡","黄金卡","白银卡","普通卡"});
             HSSFDataValidation dataValidate = new HSSFDataValidation(regions,constraint);
              sheet.addValidationData(dataValidate);    
             }*/
              
        }  
        sheet.getRow(0).setHeight(height);    
        HSSFCellStyle contentStyle = workbook.createCellStyle(); //内容样式  
        contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
        
        List<PageData> varList = (List<PageData>) model.get("varList");  
    if(varList!=null) {
        int varCount = varList.size();  
        for(int i=0; i<varCount; i++){  
            PageData vpd = varList.get(i);  
            for(int j=0;j<len;j++){  
                String varstr = vpd.getString("var"+(j+1)) != null ? vpd.getString("var"+(j+1)) : "";  
                cell = getCell(sheet, i+1, j);  
                cell.setCellStyle(contentStyle);  
                setText(cell,varstr);  
            }  
              
        }  }
          
    }

}

3.配置工具类ObjectExcelView引用的PageData工具类:

@SuppressWarnings("all")
public class PageData extends HashMap implements Map{

private static final long serialVersionUID = 1L;

Map map = null;
    HttpServletRequest request;

public PageData(HttpServletRequest request){
        this.request = request;
        Map properties = request.getParameterMap();

Map returnMap = new HashMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            System.out.println(name);
            Object valueObj = entry.getValue();
            if(null == valueObj){
                value = "";
            }else if(valueObj instanceof String[]){
                String[] values = (String[])valueObj;
                for(int i=0;i<values.length;i++){
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length()-1);
            }else{
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        map = returnMap;
    }

public PageData() {
        map = new HashMap();
    }

@Override
    public Object get(Object key) {
        Object obj = null;
        if(map.get(key) instanceof Object[]) {
            Object[] arr = (Object[])map.get(key);
            obj = request == null ? arr:(request.getParameter((String)key) == null ? arr:arr[0]);
        } else {
            obj = map.get(key);
        }
        return obj;
    }

public String getString(Object key) {
        return (String)get(key);
    }

@Override
    public Object put(Object key, Object value) {
        return map.put(key, value);
    }

@Override
    public Object remove(Object key) {
        return map.remove(key);
    }

public void clear() {
        map.clear();
    }

public boolean containsKey(Object key) {
        return map.containsKey(key);
    }

public boolean containsValue(Object value) {
        return map.containsValue(value);
    }

public Set entrySet() {
        return map.entrySet();
    }

public boolean isEmpty() {
        return map.isEmpty();
    }

public Set keySet() {
        return map.keySet();
    }

@SuppressWarnings("unchecked")
    public void putAll(Map t) {
        map.putAll(t);
    }

public int size() {
        return map.size();
    }

public Collection values() {
        return map.values();
    }
}

4.配置工具类ReadExcel读取excel中的内容:

@Component
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; }  
//    @Value("${PICTURE_ADDR}")
//    public String PICTURE_ADDR;
    
  /**
   * 验证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<OilStation> 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<OilStation> oilStationList=new ArrayList<OilStation>();
       //初始化输入流
       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里面的内容读取客户信息
          oilStationList = (List<OilStation>) 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 oilStationList;
  }
  /**
   * 根据excel里面的内容读取客户信息
   * @param is 输入流
   * @param isExcel2003 excel是2003还是2007版本
   * @return
   * @throws IOException
   */
  public  List<OilStation> getExcelInfo(InputStream is,boolean isExcel2003){
       List<OilStation> oilStationList=null;
       try{
           /** 根据版本选择创建Workbook的方式 */
           Workbook wb = null;
           //当excel是2003时
           if(isExcel2003){
               wb = new HSSFWorkbook(is); 
           }
           else{//当excel是2007时
               wb = new XSSFWorkbook(is); 
           }
           //读取Excel里面客户的信息
           oilStationList=(List<OilStation>) readExcelValue(wb);
       }
       catch (IOException e)  {  
           e.printStackTrace();  
       }  
       return oilStationList;
  }
  /**
   * 读取Excel里面客户的信息
   * @param wb
   * @return
   */
  private List<OilStation> readExcelValue(Workbook wb){ 
      //得到第一个shell  
       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<OilStation> oilStationList=new ArrayList<OilStation>();
       OilStation oilStation;
      //循环Excel行数,从第二行开始。标题不入库
       for(int r=1;r<totalRows;r++){
           Row row = sheet.getRow(r);
           if (row == null) continue;
           oilStation = new OilStation();
           
           //循环Excel的列
           for(int c = 0; c <this.totalCells; c++){    
               Cell cell = row.getCell(c);
               //System.out.println("c======:"+c+"cell:"+cell);
               if(null != cell) {
                   cell.setCellType(Cell.CELL_TYPE_STRING);
               }
             if(cell!=null && !cell.equals("")) {
                   if(c==0){
                       oilStation.setStationCode(cell.getStringCellValue());//
                   }else if(c==1){
                       oilStation.setProvince(cell.getStringCellValue());//
                   }else if(c==2){
                       oilStation.setCity(cell.getStringCellValue());//
                   }else if(c==3){
                       oilStation.setArea(cell.getStringCellValue());
                   }else if(c==4){
                      oilStation.setNotOilCode(cell.getStringCellValue());
                   }else if(c==5){
                       oilStation.setName(cell.getStringCellValue());
                   }else if(c==6){
                       if(cell.getStringCellValue() != null && cell.getStringCellValue() != ""
                               && !cell.getStringCellValue().equals("")) {
                           oilStation.setStationType(Integer.valueOf(cell.getStringCellValue()));
                       }
                   }else if(c==7){
                       oilStation.setAddress(cell.getStringCellValue());
                   }else if(c==8){
                       oilStation.setTelephone(cell.getStringCellValue());
                   }else if(c==9){//营业时间
                       if(StringUtil.isNotEmpty(cell.getStringCellValue())) {
                           oilStation.setBusinessHours(cell.getStringCellValue());
                       }
                   }else if(c==10){//营业状态
                       String s = cell.getStringCellValue();
                       if(s.contains("营业")) {
                           oilStation.setWorkStatus(1);
                       }else {
                           oilStation.setWorkStatus(2);
                       }
                       
                   }else if(c==11){
                       String s = cell.getStringCellValue();
                       if(s.contains("是")) {
                           oilStation.setAddMoney(1);
                       }else {
                           oilStation.setAddMoney(2);
                       }
                   }else if(c==12){
                       String s = cell.getStringCellValue();
                       if(s.contains("是")) {
                           oilStation.setMarket(1);
                       }else {
                           oilStation.setMarket(2);
                       }
                   }else if(c==13){
                       oilStation.setLongitude(cell.getStringCellValue());
                   }else if(c==14){
                       oilStation.setDimension(cell.getStringCellValue());
                   }else if(c==15) {
                       String s = cell.getStringCellValue();
                       oilStation.setSecond(Double.parseDouble("".equals(s.toString())?"0.00":s.toString()));
                   }else if(c==16) {
                       String s = cell.getStringCellValue();
                       oilStation.setFive(Double.parseDouble("".equals(s.toString())?"0.00":s.toString()));
                   }else if(c==17) {
                       String s = cell.getStringCellValue();
                       oilStation.setEight(Double.parseDouble("".equals(s.toString())?"0.00":s.toString()));
                   }else if(c==18) {
                       String s = cell.getStringCellValue();
                       oilStation.setZero(Double.parseDouble("".equals(s.toString())?"0.00":s.toString()));
                   }else if(c==19) {
                       String s = cell.getStringCellValue();
                       if(s.contains("是")) {
                           oilStation.setCameraNumber("1");
                       }else {
                           oilStation.setCameraNumber("2");
                       }
                       
                   }else if(c==20) {
                           oilStation.setRemark(cell.getStringCellValue());
                   }
               
           }}
           //添加客户
           oilStationList.add(oilStation);
       }
       return oilStationList;
  }

}

5.配置工具类ReadExcel引用的WDWUtil工具类,来判断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)$");  
     }  
}

6.配置读取excel文件内容的接口,并添加到数据库中:

@RequestMapping(value = "/batchAddOilStation", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
      public Map<String, Object> batchAddOilStation(@RequestParam(value = "filename") MultipartFile file,HttpServletRequest request) throws FileNotFoundException {
      Map<String, Object> map = new HashMap<>();
      try {
              
             String name = file.getOriginalFilename();
              ReadExcel read =new ReadExcel();
              List<OilStation> excelInfo = read.getExcelInfo(name, file);
               boolean flag = oilStationService.batchOwners(excelInfo);
               map.put("code", 200);
               map.put("msg", "");
               map.put("count", 1);
               map.put("data", flag);
      } catch (CodeException ce) {
          LOGGER.error(ce.getCode() + ":" + ce.getMessage());
      }
      return map;
  }

7.在jsp中需要配置:

<form>

<div class="row cl">
                    <label class="form-label col-xs-4 col-sm-2">导入车辆模板:</label>
                    <div class="formControls col-xs-8 col-sm-10">
                        <span class="btn-upload form-group">
                         <input class="input-text upload-url" type="text" name="uploadfile"
                            id="uploadfile" readonly="" nullmsg="请添加附件!">
                            <a href=" " class="btn btn-primary radius upload-btn">
                            <i class="Hui-iconfont" style="width: 150px"></i> 浏览文件</a> 
                            <input type="file" multiple="" name="filename" id="filename" class="input-file">
                        </span>
                        <label class="btn btn-primary radius " οnclick="importExcel();" style="width: 150px">下载导入模板</label>
                    </div>
                </div>

</form>

8.在js中:

function importExcel(){    
            window.location.href = "/upload/uploadExcelModel/"; 
        }

submitHandler: function(form) {
            var formData = new FormData($( "#form-add" )[0])
            $.ajax({
                type: "post",
                url: contextPath + "/owners/add",
                data: formData,
                cache: false,  
                contentType: false,  
                processData: false,
                dataType: "json",
                success: function(data) {
                    },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    //alert(errorThrown);
                    return false;
                } 
            });
            return false;
        }

java读取excel中的数据存到数据库相关推荐

  1. 使用poi读取Excel中的数据到数据库

    大家好今儿给大家带来的是使用poi读取Excel中的数据到数据库 目录 大家好今儿给大家带来的是使用poi读取Excel中的数据到数据库 1.poi简单介绍 2.poi操作excel 3.代码部分(可 ...

  2. 使用jxl来读取Excel中的数据

    使用java语言,借助第三方API来读取Excel中的数据 package com.excel;import java.io.File; import jxl.Cell; import jxl.She ...

  3. 用Eclipse读取excel中全部数据

    用Eclipse读取excel中全部数据 引包:jxl.jar import java.io.File; import java.io.FileInputStream; import java.io. ...

  4. 将excel中的数据导入数据库

    下图为java导入数据库中表的结构,其中id为自增,导入excel时excel中的数据不需要写id列,数据库会自动生成只需要写后面相对应的数据. 下表为excel导入数据库时的结构,列必须与数据库相对 ...

  5. 将excel中是数据导入数据库

    2019独角兽企业重金招聘Python工程师标准>>> 将excel中是数据导入数据库 1.利用excel生成sql语句: 列如: 1).insert: =CONCATENATE(& ...

  6. python处理微信消息导入excel_使用python读取excel中的数据,并重新写入到新的excel中...

    使用Python3运行 起初是读取excel中的数据,进行相关的计算将结果追加在后面,没有找到合适的办法,就只能采用这种读取数据,进行相关操作,重新写入的方法 1. 主要流程 (1)使用xlrd打开x ...

  7. 使用python读取excel中的数据,并绘制折线图

    使用python读取excel中的数据,并绘制折线图 做实验的时候采集到一些数据,从文本拷贝到excel,然后从十六进制转换成十进制.图表是分析数据的有利工具,使用python绘制出的图表简明美观.所 ...

  8. asp excel导入mysql_asp实现excel中的数据导入数据库

    asp实现excel中的数据导入数据库 wenjian = request.Form("select") '获取文件扩展名 ext = FileExec(wenjian) '判断文 ...

  9. java读取excel某个单元格的值_[转载]Java读取Excel中的单元格数据

    目前网上能找到的读取Excel表格中数据的两种比较好的方案:PageOffice好用开发效率高:POI免费.供大家参考,针对具体情况选择具体方案. 1. PageOffice读取excel impor ...

最新文章

  1. 封装了一套WeCenter的IOS SDK
  2. 点分治问题 ----------- 2017杭州CCPC E.Master of Subgraph[bitset+点分治]
  3. XmlSerializer 对象序列化成XML 自定义编码格式(gb2312)
  4. 一点一点看JDK源码(四)java.util.ArrayList 中篇
  5. VTK:可视化算法之PineRootConnectivity
  6. JDK1.5中的线程池(java.util.concurrent.ThreadPoolExecutor
  7. Spark _22 _创建DataFrame的几种方式(一)
  8. element手机验证格式_Laravel 自定义封装表单验证类
  9. 织梦黑色互联网建站设计模板
  10. tomcat内存优化
  11. 百度Map与HT for Web结合的GIS网络拓扑应用
  12. Angular 项目中使用 ECharts 图表示例
  13. LeetCode Excel Sheet Column Number 表列数
  14. Git和Cmake下载超级慢的解决方案
  15. 五位数电话号码以及中国各市区号
  16. 裤子尺码对照表eur40_裤子尺寸对照表,衣服尺寸对照表,服装尺寸对照表 - 尺码对照表...
  17. 翼支付门户架构之搭建SpringMvc环境
  18. 计算机系统基础-入门
  19. 【渝粤题库】国家开放大学2021春2196社会调查研究与方法题目
  20. knn鸢尾花数据集java_1.从鸢尾花数据集与KNN说起

热门文章

  1. JTable调整列宽
  2. 调优您的 LAMP 应用程序的 5 种简单方法
  3. flask html下拉列表,如何使用Flask和HTML从python列表创建下拉菜单
  4. anaconda 历史版本_【windows】下Anaconda详细安装过程
  5. 7系列mrcc xilinx_XILINX 7系列FPGA_时钟篇
  6. java递增不使用循环_[转]Java 8:不要再用循环了
  7. word服务器草稿位置有必要更改么,如何改变WIN10常用文档的默认位置?真的有必要更改吗?...
  8. python查询在查询_python 查询,子查询以及1对多查询
  9. python 视频 灰度 伽玛_moviepy音视频剪辑:lum_contrast什么时候使用以及图像处理什么时候需要调整亮度与对比度...
  10. 七十二、Vuex实现双父组件数据共享、localStorage、mapActions和keep-alive