关闭

POI教程-简单操作

831人阅读 评论(0) 收藏 举报
分类:

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



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:57578次
    • 积分:1096
    • 等级:
    • 排名:千里之外
    • 原创:53篇
    • 转载:6篇
    • 译文:0篇
    • 评论:16条
    文章分类