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();
		}
	}

 

 

 

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值