java 讀寫excel文件

用poi讀取excel文件 將文件讀取爲數據流,然後採用流處理獲得文件內容。poi需要引入jar包

寫excel文件

public void writeExcel(String filePath,String fileType) throws IOException{
		System.out.println("writeExcel");
		Workbook wb=null;
		if(fileType.equals("xls")){
			wb=new HSSFWorkbook();
		}
		else{
			wb=new XSSFWorkbook();
		}
		
		Sheet sheet=wb.createSheet("sheet1");
		for(int i=0;i<5;i++){
			Row row=sheet.createRow(i);
			for(int j=0;j<5;j++){
				Cell cell=row.createCell(j);
				cell.setCellValue("test"+j);
			}
		}
		OutputStream ou=new FileOutputStream(filePath);
		wb.write(ou);
		ou.close();
	}


讀excel文件

public void readExcel(String filePath,String fileType) throws IOException{
		InputStream in=new FileInputStream(filePath);
		Workbook wb=null;
		if(fileType.equals("xls")){
			wb=new HSSFWorkbook(in);
		}
		else if(fileType.equals("xlsx")){
			wb=new XSSFWorkbook(in);
		}
		for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
			Sheet sheet=wb.getSheetAt(numSheet);
			for(int rowNum=0;rowNum<sheet.getLastRowNum();rowNum++){
				Row row=sheet.getRow(rowNum);
				for(int cellNum=0;cellNum<row.getLastCellNum();cellNum++){
					String s=getValue(row.getCell(cellNum));
					System.out.println(s);
				}
			}
		}
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章