如何在java中利用poi将Excel数据导入到数据库中
创始人
2024-12-26 06:22:11
0次

1 先手要制定一个Excel 模板 把模板放入javaWeb工程的某一个目录下如图:

如何在java中利用poi将Excel数据导入到数据库中

2 模板建好了后,先实现模板下载功能 下面是页面jsp代码在这里只贴出部分代码



  book/dishes/backstageversion/list!importExcel" method="post" enctype="multipart/form-data"
   class="form-search"  onsubmit="loading('正在导入,请稍等...');">
   

                  book/dishes/backstageversion/list!exportOrder" rel="external nofollow" rel="external nofollow" >下载模板   


  book/dishes/backstageversion/list!importExcel" method="post" enctype="multipart/form-data"
   class="form-search"  onsubmit="loading('正在导入,请稍等...');">
   

                  book/dishes/backstageversion/list!exportOrder" rel="external nofollow" rel="external nofollow" >下载模板   

下面是js


 /res/admin/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet" type="text/css" /> 
 /res/admin/css/xy_css.css" rel="external nofollow" rel="stylesheet" type="text/css">
 /res/admin/css/font-awesome.min.css" rel="external nofollow" rel="stylesheet" type="text/css">
 /res/admin/js/jquery.min.js">
 /res/admin/js/bootstrap.min.js">
 /res/admin/jquery-select2/3.4/select2.css" rel="external nofollow" rel="stylesheet" type="text/css" /> 
 /res/admin/jquery-select2/3.4/select2.min.js">
 /res/admin/jquery-select2/3.4/select2_locale_zh-CN.js">
 
 
 
  $(document).ready(function (){//加载页面时执行select2
   $("select").select2();
   //弹出导出窗口
   $("#btnImport").click(function(){
    var importStallId = $("#stallId option:selected").val();
    var importCompanyId = $("#companyId option:selected").val();
    $("#importCompanyId").val(importCompanyId);
    $("#importStallId").val(importStallId);
    if(importStallId==null || importStallId==""){
     alert("请选择档口");
    }else{
     layer.open({
      type: 1,
      skin: 'layui-layer-rim', //加上边框
      area: ['600px', '350px'], //宽高
      content: $('#importBox')
     });
    }
   });
  });

3 下面是后台代码Action 类

一:下载模板代码

/**
  * 下载模板
  * @throws IOException 
  */
 public void exportOrder() throws IOException{
  HttpServletRequest request = ServletActionContext.getRequest();
  HttpServletResponse response = ServletActionContext.getResponse();
  File file = null;
  InputStream inputStream = null;
  ServletOutputStream out = null;
  try {
   request.setCharacterEncoding("UTF-8");
   String realPath = ServletActionContext.getServletContext().getRealPath("/");
   file = new File(realPath+"WEB-INF/mailtemplate/dishes.xlsx");
   inputStream = new FileInputStream(file);
   response.setCharacterEncoding("utf-8");
   response.setContentType("application/msexcel");
   response.setHeader("content-disposition", "attachment;filename="
     + URLEncoder.encode("菜品导入" + ".xlsx", "UTF-8"));
   out = response.getOutputStream();
   byte[] buffer = new byte[512]; // 缓冲区
   int bytesToRead = -1;
   // 通过循环将读入的Excel文件的内容输出到浏览器中
   while ((bytesToRead = inputStream.read(buffer)) != -1) {
    out.write(buffer, 0, bytesToRead);
   }
   out.flush();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (inputStream != null)
    inputStream.close();
   if (out != null)
    out.close();
   if (file != null)
    file.delete(); // 删除临时文件
  }
 }

二: 导入代码

/**
  * 导入
  * @throws IOException 
  */
 public void importExcel() throws IOException {
  List dishesList = getDishesList(file);
  if(dishesList !=null && dishesList.size()>0){
   for(Dishes dishes : dishesList){
    targetService.add(dishes);
   }
  }
  String basePath = ServletActionContext.getServletContext().getContextPath();
  ServletActionContext.getResponse().sendRedirect(basePath + "/book/dishes/backstageversion/list");
 }
 /**
  * 读取Excel数据 
  * @param filePath
  * @return List
  * @throws IOException
  */
 private List getDishesList(String filePath) throws IOException {
  XSSFWorkbook workBook= null;
  InputStream is = new FileInputStream(filePath);
  try {
   workBook = new XSSFWorkbook(is);
  } catch (Exception e) {
   e.printStackTrace();
  }
  Dishes dishes=null;
  List dishesList = new ArrayList();
  //循环工作表sheet
  //List picturesList = getPicturesList(workBook);//获取所有图片
  for(int numShett = 0;numShett pictureDataMap = getPictureDataMap(sheet, workBook);
if(sheet==null){
    continue;
   }
   //循环Row
   for(int rowNum=1;rowNum<=sheet.getLastRowNum();rowNum++){
    Row row = sheet.getRow(rowNum);
    if(row==null){
     continue;
    }
    
    dishes = new Dishes();
    //Cell
    Cell dishesName = row.getCell(0);
    if(dishesName==null){
     continue;
    }
    dishes.setName(getValue(dishesName));//菜品名称
    Cell price = row.getCell(1);
    if(price==null){
     continue;
    }
    dishes.setPrice(Double.parseDouble(getValue(price)));//优惠价格
    Cell oldPrice = row.getCell(2);
    if(oldPrice==null){
     continue;
    }
    dishes.setOldPrice(Double.parseDouble(getValue(oldPrice)));//原价格
    Cell summary = row.getCell(3);
    if(summary==null){
     continue;
    }
    dishes.setSummary(getValue(summary));//菜品描述
    Cell online = row.getCell(4);
    if(online==null){
     continue;
    }
    dishes.setOnline(Integer.parseInt(getValue(online)));//是否上下架
    Cell packCharge = row.getCell(5);
    if(packCharge==null){
     continue;
    }
    dishes.setPackCharge(Double.parseDouble(getValue(packCharge)));//打包费
    Cell stockNumber = row.getCell(6);
    if(stockNumber==null){//库存为必填
     continue;
    }
    dishes.setStockNumber(Integer.parseInt(getValue(stockNumber)));//每餐库存
    Cell immediateStock = row.getCell(7);
    if(immediateStock==null){//当前库存
     continue;
    }
    dishes.setImmediateStock(Integer.parseInt(getValue(immediateStock)));//当前库存
    Cell purchaseLimit = row.getCell(8);
    if(purchaseLimit==null){
     continue;
    }
    dishes.setPurchaseLimit(Integer.parseInt(getValue(purchaseLimit)));//限购数量
    Cell restrictionType = row.getCell(9);
    
    if(restrictionType==null){
     continue;
    }
    dishes.setRestrictionType(Integer.parseInt(getValue(restrictionType)));//限购方式
    Cell sort = row.getCell(10);
    if(sort==null){
     continue;
    }
    dishes.setSort(Integer.parseInt(getValue(sort)));//排序
    Cell contents = row.getCell(11);
    if(contents==null){
     continue;
    }
    dishes.setContents(getValue(contents));//菜品详情
    dishes.setCreateTime(new Date());
    Company company = companyService.load(importCompanyId);
    Stall stall = stallService.load(importStallId);
    dishes.setCompany(company);
    dishes.setStall(stall);

                 //set 图片                 PictureData pictureData = pictureDataMap.get(rowNum+"");                 if(pictureData !=null){                  String upImageUrl = UpImage(pictureData.getData());                  dishes.setImage(upImageUrl);                 }
    dishesList.add(dishes);
   }
  }
  return dishesList;
 }
 /**
  * 得到Excel表中的值
  * @param hssfCell
  * @return String
  */
 @SuppressWarnings("unused")
 private String getValue(Cell cell){
  DecimalFormat df = new DecimalFormat("###################.###########");
  if(cell.getCellType()==cell.CELL_TYPE_BOOLEAN){
   return String.valueOf(cell.getBooleanCellValue());
  }
  if(cell.getCellType()==cell.CELL_TYPE_NUMERIC){
   return String.valueOf(df.format(cell.getNumericCellValue()));
  }else{
   return String.valueOf(cell.getStringCellValue());
  }
 }

4 get set 方法

 private String file;
 
 private Long importCompanyId;
 private Long importStallId;
public String getFile() {
  return file;
 }

 public void setFile(String file) {
  this.file = file;
 }

 public Long getImportCompanyId() {
  return importCompanyId;
 }

 public void setImportCompanyId(Long importCompanyId) {
  this.importCompanyId = importCompanyId;
 }

 public Long getImportStallId() {
  return importStallId;
 }

 public void setImportStallId(Long importStallId) {
  this.importStallId = importStallId;
 }

公司需求改变要增加导入图片到又拍云服务器,所以下面增加读取excel图片

/**
  * 读取Excel 中图片
  * @param sheet
  * @param workBook
  * @return
  */
 private Map getPictureDataMap(XSSFSheet sheet,XSSFWorkbook workBook){
  Map map = new HashMap();
  for(POIXMLDocumentPart dr : sheet.getRelations()){
   if(dr instanceof XSSFDrawing){
    XSSFDrawing drawing = (XSSFDrawing) dr;
    List shapesList = drawing.getShapes();
    if(shapesList !=null && shapesList.size()>0){
     for(XSSFShape shape : shapesList){
      XSSFPicture pic = (XSSFPicture) shape;
      XSSFClientAnchor anchor = pic.getPreferredSize();
      CTMarker cTMarker = anchor.getFrom();
      String picIndex = cTMarker.getRow()+"";
      map.put(picIndex, pic.getPictureData());
     }
    }
   }
  }
  return map;
 }
/**
  * 上传图片到又拍云
  * @param bytes
  * @return
  */
 private String UpImage(byte[] bytes){
  String fileName = UUID.randomUUID().toString() + ".jpg";
  String uploadURL = UpYunClient.upload(fileName, bytes);
  return uploadURL;
 }

上述就是小编为大家分享的如何在java中利用poi将Excel数据导入到数据库中了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注行业资讯频道。

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...