자바 poi 를 사용 하여 엑셀 데 이 터 를 데이터베이스 로 가 져 오 는 절차

제 개인 용 컴퓨터 에 설 치 된 Excel 은 2016 버 전이 기 때문에 이곳 은 XSSF 방식 으로 가 져 왔 습 니 다.
1.먼저 Excel 템 플 릿 을 만들어 서 자바 웹 프로젝트 의 한 디 렉 터 리 에 템 플 릿 을 넣 어야 합 니 다.그림:

2.템 플 릿 이 만들어 진 후에 템 플 릿 다운로드 기능 을 먼저 실현 합 니 다.다음은 페이지 jsp 코드 입 니 다.여기에 일부 코드 만 붙 입 니 다.

<!-- excel         -->
<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('    ,   ...');"><br/>
   <input id="uploadFile" name="file" type="file" style="width:330px"/><br/><br/>  
   <input id="btnImportSubmit" class="btn btn-primary" type="submit" value="     "/>
   <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         -->
<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('    ,   ...');"><br/>
   <input id="uploadFile" name="file" type="file" style="width:330px"/><br/><br/>  
   <input id="btnImportSubmit" class="btn btn-primary" type="submit" value="     "/>
   <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 (){//       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<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   
  * @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>();
  //     sheet
  //List<XSSFPictureData> picturesList = getPicturesList(workBook);//      
  for(int numShett = 0;numShett<workBook.getNumberOfSheets();numShett++){
   XSSFSheet sheet = workBook.getSheetAt(numShett);
             //                   Map<String, PictureData> 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    
  * @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;
 }
주의:Poi 를 사용 하 세 요.  jar 3.9 버 전 입 니 다.그렇지 않 으 면 그림 코드 를 읽 으 면 오류 가 발생 합 니 다.
이상 은 자바 가 poi 를 사용 하여 엑셀 데 이 터 를 데이터베이스 에 가 져 오 는 절차 에 대한 상세 한 내용 입 니 다.자바 가 엑셀 데 이 터 를 데이터베이스 에 가 져 오 는 데 관 한 자 료 는 다른 관련 글 을 주목 하 십시오!

좋은 웹페이지 즐겨찾기