最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java 使用poi 導(dǎo)入Excel數(shù)據(jù)到數(shù)據(jù)庫(kù)的步驟

 更新時(shí)間:2020年12月14日 11:55:33   作者:阿若蜜意  
這篇文章主要介紹了java 使用poi 導(dǎo)入Excel 數(shù)據(jù)到數(shù)據(jù)庫(kù)的步驟,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下

由于我個(gè)人電腦裝的Excel是2016版本的,所以這地方我使用了XSSF 方式導(dǎo)入 。

1 先手要制定一個(gè)Excel 模板 把模板放入javaWeb工程的某一個(gè)目錄下如圖:

2 模板建好了后,先實(shí)現(xiàn)模板下載功能 下面是頁(yè)面jsp代碼在這里只貼出部分代碼

<!-- excel 導(dǎo)入小模塊窗口 -->
<div id="importBox" class="" style="display: none;">
  <form id="importForm" action="<%=basePath%>book/dishes/backstageversion/list!importExcel" method="post" enctype="multipart/form-data"
   class="form-search" style="padding-left:20px;text-align:center;" onsubmit="loading('正在導(dǎo)入,請(qǐng)稍等...');"><br/>
   <input id="uploadFile" name="file" type="file" style="width:330px"/><br/><br/>  
   <input id="btnImportSubmit" class="btn btn-primary" type="submit" value=" 導(dǎo) 入 "/>
   <input type="hidden" id="importCompanyId" name="importCompanyId" value=""/>
   <input type="hidden" id="importStallId" name="importStallId" value=""/>
   <a href="<%=basePath%>book/dishes/backstageversion/list!exportOrder" rel="external nofollow" rel="external nofollow" >下載模板</a>
  </form>
</div>
<!-- excel 導(dǎo)入小模塊窗口 -->
<div id="importBox" class="" style="display: none;">
  <form id="importForm" action="<%=basePath%>book/dishes/backstageversion/list!importExcel" method="post" enctype="multipart/form-data"
   class="form-search" style="padding-left:20px;text-align:center;" onsubmit="loading('正在導(dǎo)入,請(qǐng)稍等...');"><br/>
   <input id="uploadFile" name="file" type="file" style="width:330px"/><br/><br/>  
   <input id="btnImportSubmit" class="btn btn-primary" type="submit" value=" 導(dǎo) 入 "/>
   <input type="hidden" id="importCompanyId" name="importCompanyId" value=""/>
   <input type="hidden" id="importStallId" name="importStallId" value=""/>
   <a href="<%=basePath%>book/dishes/backstageversion/list!exportOrder" rel="external nofollow" rel="external nofollow" >下載模板</a>
  </form>
</div>

下面是js

<!-- Bootstrap -->
 <link href="<%=path %>/res/admin/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet" type="text/css" /> 
 <link href="<%=path %>/res/admin/css/xy_css.css" rel="external nofollow" rel="stylesheet" type="text/css">
 <link href="<%=path %>/res/admin/css/font-awesome.min.css" rel="external nofollow" rel="stylesheet" type="text/css">
 <script src="<%=path %>/res/admin/js/jquery.min.js"></script>
 <script src="<%=path %>/res/admin/js/bootstrap.min.js"></script>
 <link href="<%=path %>/res/admin/jquery-select2/3.4/select2.css" rel="external nofollow" rel="stylesheet" type="text/css" /> 
 <script src="<%=path %>/res/admin/jquery-select2/3.4/select2.min.js"></script>
 <script src="<%=path %>/res/admin/jquery-select2/3.4/select2_locale_zh-CN.js"></script>
 
 <script type="text/javascript" src="<%=basePath%>res/admin/js/layer/layer.js"></script>
 <script type="text/javascript">
  $(document).ready(function (){//加載頁(yè)面時(shí)執(zhí)行select2
   $("select").select2();
   //彈出導(dǎo)出窗口
   $("#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("請(qǐng)選擇檔口");
    }else{
     layer.open({
      type: 1,
      skin: 'layui-layer-rim', //加上邊框
      area: ['600px', '350px'], //寬高
      content: $('#importBox')
     });
    }
   });
  });

3 下面是后臺(tái)代碼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("菜品導(dǎo)入" + ".xlsx", "UTF-8"));
   out = response.getOutputStream();
   byte[] buffer = new byte[512]; // 緩沖區(qū)
   int bytesToRead = -1;
   // 通過(guò)循環(huán)將讀入的Excel文件的內(nèi)容輸出到瀏覽器中
   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(); // 刪除臨時(shí)文件
  }
 }

二: 導(dǎo)入代碼

/**
  * 導(dǎo)入
  * @throws IOException 
  */
 public void importExcel() throws IOException {
  List<Dishes> 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數(shù)據(jù) 
  * @param filePath
  * @return List
  * @throws IOException
  */
 private List<Dishes> 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<Dishes> dishesList = new ArrayList<Dishes>();
  //循環(huán)工作表sheet
  //List<XSSFPictureData> picturesList = getPicturesList(workBook);//獲取所有圖片
  for(int numShett = 0;numShett<workBook.getNumberOfSheets();numShett++){
   XSSFSheet sheet = workBook.getSheetAt(numShett);
             //調(diào)用獲取圖片             Map<String, PictureData> pictureDataMap = getPictureDataMap(sheet, workBook);
if(sheet==null){
    continue;
   }
   //循環(huán)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)));//優(yōu)惠價(jià)格
    Cell oldPrice = row.getCell(2);
    if(oldPrice==null){
     continue;
    }
    dishes.setOldPrice(Double.parseDouble(getValue(oldPrice)));//原價(jià)格
    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)));//打包費(fèi)
    Cell stockNumber = row.getCell(6);
    if(stockNumber==null){//庫(kù)存為必填
     continue;
    }
    dishes.setStockNumber(Integer.parseInt(getValue(stockNumber)));//每餐庫(kù)存
    Cell immediateStock = row.getCell(7);
    if(immediateStock==null){//當(dāng)前庫(kù)存
     continue;
    }
    dishes.setImmediateStock(Integer.parseInt(getValue(immediateStock)));//當(dāng)前庫(kù)存
    Cell purchaseLimit = row.getCell(8);
    if(purchaseLimit==null){
     continue;
    }
    dishes.setPurchaseLimit(Integer.parseInt(getValue(purchaseLimit)));//限購(gòu)數(shù)量
    Cell restrictionType = row.getCell(9);
    
    if(restrictionType==null){
     continue;
    }
    dishes.setRestrictionType(Integer.parseInt(getValue(restrictionType)));//限購(gòu)方式
    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;
 }

公司需求改變要增加導(dǎo)入圖片到又拍云服務(wù)器,所以下面增加讀取excel圖片

/**
  * 讀取Excel 中圖片
  * @param sheet
  * @param workBook
  * @return
  */
 private Map<String, PictureData> getPictureDataMap(XSSFSheet sheet,XSSFWorkbook workBook){
  Map<String, PictureData> map = new HashMap<String,PictureData>();
  for(POIXMLDocumentPart dr : sheet.getRelations()){
   if(dr instanceof XSSFDrawing){
    XSSFDrawing drawing = (XSSFDrawing) dr;
    List<XSSFShape> 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;
 }

注意:請(qǐng)用Poi  jar 3.9 版本 不然讀取圖片代碼會(huì)報(bào)錯(cuò)

以上就是java 使用poi 導(dǎo)入Excel 數(shù)據(jù)到數(shù)據(jù)庫(kù)的步驟的詳細(xì)內(nèi)容,更多關(guān)于Java 導(dǎo)入Excel 數(shù)據(jù)到數(shù)據(jù)庫(kù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • MyBatis-Plus結(jié)合Layui實(shí)現(xiàn)分頁(yè)方法

    MyBatis-Plus結(jié)合Layui實(shí)現(xiàn)分頁(yè)方法

    MyBatis-Plus 使用簡(jiǎn)單,本文主要介紹使用 service 中的 page 方法結(jié)合 Layui 前端框架實(shí)現(xiàn)分頁(yè)效果,具有一定的參考價(jià)值,感興趣的可以了解一下
    2021-08-08
  • java如何將map數(shù)據(jù)存入到實(shí)體類對(duì)象中

    java如何將map數(shù)據(jù)存入到實(shí)體類對(duì)象中

    在Java編程中,經(jīng)常需要將Map集合中的數(shù)據(jù)轉(zhuǎn)換為實(shí)體類對(duì)象,這可以通過(guò)反射機(jī)制實(shí)現(xiàn),即通過(guò)遍歷Map對(duì)象,使用反射根據(jù)鍵名對(duì)應(yīng)實(shí)體類的屬性名,動(dòng)態(tài)調(diào)用setter方法將值設(shè)置到實(shí)體對(duì)象中,這樣的操作使得數(shù)據(jù)從Map結(jié)構(gòu)轉(zhuǎn)移到了具體的JavaBean中,便于后續(xù)的操作和管理
    2024-09-09
  • Java中的內(nèi)部類使用詳情

    Java中的內(nèi)部類使用詳情

    說(shuō)起內(nèi)部類這個(gè)詞,想必很多人都不陌生,但是又會(huì)覺(jué)得不熟悉。原因是平時(shí)編寫(xiě)代碼時(shí)可能用到的場(chǎng)景不多,用得最多的是在有事件監(jiān)聽(tīng)的情況下,并且即使用到也很少去總結(jié)內(nèi)部類的用法。今天我們就來(lái)一探究竟
    2022-03-03
  • Spring Security如何基于Authentication獲取用戶信息

    Spring Security如何基于Authentication獲取用戶信息

    這篇文章主要介紹了Spring Security如何基于Authentication獲取用戶信息,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-03-03
  • MybatisPlus+Postgresql整合的幾個(gè)坑及解決

    MybatisPlus+Postgresql整合的幾個(gè)坑及解決

    這篇文章主要介紹了MybatisPlus+Postgresql整合的幾個(gè)坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Java使用JDBC實(shí)現(xiàn)Oracle用戶認(rèn)證的方法詳解

    Java使用JDBC實(shí)現(xiàn)Oracle用戶認(rèn)證的方法詳解

    這篇文章主要介紹了Java使用JDBC實(shí)現(xiàn)Oracle用戶認(rèn)證的方法,結(jié)合實(shí)例形式分析了java使用jdbc實(shí)現(xiàn)數(shù)據(jù)庫(kù)連接、建表、添加用戶、用戶認(rèn)證等操作流程與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2017-08-08
  • java必懂的冷知識(shí)點(diǎn)之Base64加密與解密

    java必懂的冷知識(shí)點(diǎn)之Base64加密與解密

    這篇文章主要介紹了java必懂的冷知識(shí)點(diǎn)之Base64加密與解密的相關(guān)資料,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • JAVA實(shí)現(xiàn)漢字轉(zhuǎn)拼音功能代碼實(shí)例

    JAVA實(shí)現(xiàn)漢字轉(zhuǎn)拼音功能代碼實(shí)例

    這篇文章主要介紹了JAVA實(shí)現(xiàn)漢字轉(zhuǎn)拼音功能代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05
  • Springboot項(xiàng)目中定時(shí)任務(wù)的四種實(shí)現(xiàn)方式詳解

    Springboot項(xiàng)目中定時(shí)任務(wù)的四種實(shí)現(xiàn)方式詳解

    Spring的@Scheduled注解是一種非常簡(jiǎn)單和便捷的實(shí)現(xiàn)定時(shí)任務(wù)的方式,通過(guò)在方法上添加@Scheduled注解,我們可以指定方法在特定的時(shí)間間隔或固定的時(shí)間點(diǎn)執(zhí)行,本文給大家介紹Springboot項(xiàng)目中定時(shí)任務(wù)的四種實(shí)現(xiàn)方式,感興趣的的朋友一起看看b
    2024-02-02
  • Java中判斷集合是否相等的幾種方法詳解

    Java中判斷集合是否相等的幾種方法詳解

    這篇文章主要介紹了Java中判斷集合是否相等的幾種方法詳解,在平時(shí)的開(kāi)發(fā)中,可能會(huì)遇到需要判斷兩個(gè)集合是否相等的需求,那么本文就來(lái)詳細(xì)講解一下幾種實(shí)現(xiàn)方法,需要的朋友可以參考下
    2023-08-08

最新評(píng)論

漳州市| 清水县| 高陵县| 图木舒克市| 瑞金市| 碌曲县| 白水县| 蓝田县| 天祝| 外汇| 黑山县| 交口县| 乌恰县| 凉城县| 宽甸| 林芝县| 西充县| 枣庄市| 上犹县| 塘沽区| 乌鲁木齐县| 虹口区| 武安市| 苍梧县| 肇源县| 伊吾县| 巧家县| 许昌市| 密云县| 新泰市| 综艺| 庆云县| 阿拉善左旗| 柳林县| 汝阳县| 边坝县| 获嘉县| 沙河市| 林口县| 进贤县| 襄樊市|