java 中excel导入数据库

1.首先将excel文件上传到服务器中;

 

 public String conImportExcel(MultipartFile file,HttpServletRequest request,HttpServletResponse response){
		 //String fileName = request.getParameter("fileName");
		 String fileAbuolutePath=null;
		 try {  
	        String originalFilename = file.getOriginalFilename();
	        File filePath = new File(getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes/", "/static/upload/temp"));
			if (!filePath.exists()) {
				filePath.mkdirs();
			}                      
			fileAbuolutePath=filePath.getAbsolutePath() + "\\" + originalFilename;
			file.transferTo(new File(fileAbuolutePath));
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		 System.out.println(fileAbuolutePath);
		 return fileAbuolutePath;
	 }
public HSSFWorkbook getExcelData(MultipartFile file,HttpServletRequest request,HttpServletResponse response){
		String path=conImportExcel(file,request,response);
		File f = new File(path);
	       FileInputStream excel=null;
	       HSSFWorkbook book = null;
		try {
			 excel = new FileInputStream(f);
			 book=new HSSFWorkbook(excel);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return  book; 
	}

 2.读取excel中的数据

 

public void importExcelData(HSSFWorkbook book) {
		// TODO Auto-generated method stub
		HSSFSheet sheet = book.getSheetAt(0);
		int startReadRow = 0;
		int lastRowNum = sheet.getLastRowNum();
		for(int i = startReadRow; i <= lastRowNum; i++){
			Sensors sensor=new Sensors();
			 HSSFRow row = sheet.getRow(i);
			 HSSFCell c0=row.getCell(0);
			 String v0= ExcelTool.getExcelValue(c0);
			 HSSFCell c1=row.getCell(1);
			 isMergedRegion(sheet,i,c1.getColumnIndex());
			 String v1= ExcelTool.getExcelValue(c1);
			 HSSFCell c2=row.getCell(2);
			 String v2= ExcelTool.getExcelValue(c2);
		}
	}
	
	public boolean isMergedRegion(HSSFSheet sheet,int row, int cell ){
		int sheetMergeCount =sheet.getNumMergedRegions();
		for(int i=0;i<sheetMergeCount;i++){
			CellRangeAddress ca=sheet.getMergedRegion(i); 
			int firstRow=ca.getFirstRow();   //起始行
			int lastRow=ca.getLastRow();     //结束行
			int firstColumn=ca.getFirstColumn();
			int lastColumn=ca.getLastColumn();
			System.out.println(firstRow+""+lastRow+""+firstColumn+""+lastColumn);
		}
		return false;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值