JavaでExcelの読み書きが行えるApache POI

業務ではよくCSVが使われることが多いと思いますが、
EXCELの方がいろんな用途で使えそうですね


http://poi.terra-intl.com/
http://www.apache.org/dyn/closer.cgi/jakarta/poi/release/


以下のファイルをダウンロード
poi-bin-3.0-FINAL-20070503.zip


Excelファイルとして書き込む場合

FileOutputStream outs = null;
try {
	outs = new FileOutputStream("output.xls");

	HSSFWorkbook wb = new HSSFWorkbook();
	HSSFSheet sheet = wb.createSheet();
	wb.setSheetName(0, "test");

	HSSFRow row = sheet.createRow(0);
	row.createCell((short)0).setCellValue(new HSSFRichTextString("あいうえお"));

	wb.write(outs);

} catch (Exception e) {
	e.printStackTrace();
} finally {
	try {
		if (outs != null) {
			outs.close();
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}


Excelファイルを読み込む場合

FileInputStream ins = null;
try {
	ins = new FileInputStream("output.xls");

	HSSFWorkbook wb = new HSSFWorkbook(ins);
	HSSFSheet sheet = wb.getSheet("test");

	HSSFRow row = sheet.getRow(0);
	String text = row.getCell((short)0).getRichStringCellValue().toString();

	System.out.println(text);

} catch(Exception e) {
	e.printStackTrace();
} finally {
	try {
		if (ins != null) {
			ins.close();
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}


書式などちょっと凝ったことを使用とすると、やや面倒な
感じですが、結構便利に使えました