1.首先将excel文件上传到服务器中;
?
class="java"> 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; }
?