excel import database in java

1. First upload the excel file to the server;

 

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. Read data in 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(); //Start row
			int lastRow=ca.getLastRow(); //End row
			int firstColumn=ca.getFirstColumn();
			int lastColumn=ca.getLastColumn();
			System.out.println(firstRow+""+lastRow+""+firstColumn+""+lastColumn);
		}
		return false;
	}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326073510&siteId=291194637