java读写Excel

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值