Apache Jakarta의 하위 프로젝트 POI 싸이트(http://jakarta.apache.org/poi/)에서
api를 다운받는다. (현재 가능한 버전이 2004년 8월 4일 릴리즈된 2.5.1임)
1. 읽기
import org.apache.poi.hssf.usermodel.*;
import java.io.*;
class ExcelTestRead
{
public static void main(String[] args)
{
try {
//입력 스트림 생성
FileInputStream fileInput = new FileInputStream("test.xls");
//Workbook 읽기
HSSFWorkbook workbook = new HSSFWorkbook(fileInput);
fileInput.close();
//Sheet 읽기
HSSFSheet sheet = workbook.getSheetAt(0);
//Row 읽기
HSSFRow row = sheet.getRow(0);
//Cell 3개 읽기
HSSFCell cell1 = row.getCell((short)0);
String string1 = cell1.getStringCellValue();
HSSFCell cell2 = row.getCell((short)1);
String string2 = cell2.getStringCellValue();
HSSFCell cell3 = row.getCell((short)2);
String string3 = cell3.getStringCellValue();
System.out.println("Excel File의 내용: "+string1+" | "+string2+" | "+string3);
}
catch(Exception e) {
System.out.println(e);
}
}
}
2. 쓰기
import org.apache.poi.hssf.usermodel.*;
import java.io.*;
class ExcelTestWrite
{
public static void main(String[] args)
{
try {
//Workbook 생성
HSSFWorkbook workbook = new HSSFWorkbook();
//Sheet를 생성
HSSFSheet sheet = workbook.createSheet("TEST SHEET");
//Row 생성
HSSFRow row = sheet.createRow(0);
//Cell 3개 생성
HSSFCell cell1 = row.createCell((short)0);
cell1.setCellValue("cell 1");
HSSFCell cell2 = row.createCell((short)1);
cell2.setCellValue("cell 2");
HSSFCell cell3 = row.createCell((short)2);
cell3.setCellValue("cell 3");
//파일로 쓰기
FileOutputStream fileOutput = new FileOutputStream("test.xls");
workbook.write(fileOutput);
fileOutput.close();
}
catch(Exception e) {
System.out.println(e);
}
}
}
[출처] JAVA에서 Excel 파일 읽기/쓰기|작성자 곰팅이