POI教程-简单操作

适用于 excel 2003

 

创建 excel 表

public void write() throws IOException{
		//1.创建工作簿
		HSSFWorkbook workbook = new HSSFWorkbook();
		//2.创建工作表
		HSSFSheet sheet = workbook.createSheet("hello world");
		//3.创建行
		HSSFRow row = sheet.createRow(1);
		//4.创建单元格
		HSSFCell cell = row.createCell(1);
		cell.setCellValue("hell world!");
		//输出到盘符
		FileOutputStream outputStream = new FileOutputStream("D:\\itcast\\测试.xls");
		workbook.write(outputStream);
		workbook.close();
		outputStream.close();
	}

 

读取excle 表

public void read() throws IOException{
		
		FileInputStream inputStream = new FileInputStream("D:\\itcast\\测试.xls");
		//1.读取工作簿
		HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
		//2.读取工作表
		HSSFSheet sheet = workbook.getSheetAt(0);
		//3.创读取行
		HSSFRow row = sheet.getRow(1);
		//4.读取单元格
		HSSFCell cell = row.getCell(1);
		System.out.println(cell.getStringCellValue());
		//输出到盘符
		workbook.close();
		inputStream.close();
	}

 

以下方式为兼容任何版本

public void test() throws IOException{
		String fileName = "D:\\itcast\\测试.xls";
		FileInputStream inputStream = new FileInputStream("D:\\itcast\\测试.xls");
		//正则表达式 判断 文件时 xls 2003   还是 xlsx  2007
		if(fileName.matches("^.+\\.(?i)((xls)|(xlsx))$")){
			boolean is03eExcel = fileName.matches("^.+\\.(?i)((xls))$");
			//1.读取工作簿
			Workbook workbook = is03eExcel ? new HSSFWorkbook(inputStream):new XSSFWorkbook(inputStream);
			//2.读取工作表
			Sheet sheet = workbook.getSheetAt(0);
			//3.创读取行
			Row row = sheet.getRow(1);
			//4.读取单元格
			Cell cell = row.getCell(1);
			System.out.println(cell.getStringCellValue());
			//输出到盘符
			workbook.close();
			inputStream.close();
		}
	}

 

 

 

 

你可能感兴趣的:(java)