POI 엑셀(Excel)문서 처리 패키지

황제낙엽 2007.01.22 14:38 조회 수 : 1334 추천:109

sitelink1  
sitelink2  
sitelink3  
extra_vars4  
extra_vars5  
extra_vars6  
이하의 두 패키지는 MicroSoft의 엑셀포맷문서를 처리하기 위한 프로그램이다.
Standard CSV 문서의 경우 오류를 발생한다.


Jexcel
http://www.andykhan.com

http://www.andykhan.com/jexcelapi/tutorial.html
/**
 *  Description of the Class
 *
 *@author     
 *@created    2002/ 10/ 17 
 */


import java.io.File;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;


public class ExcelReadSecond {
 
  /**
   *  The main program for the ExcelRead class
   *
   *@param  args                       The command line arguments
   *@exception  Exception            Description of the Exception
   */
  public static void main(String[] args) throws Exception {

    // 쓰기 테스트
//    WritableWorkbook workbook = Workbook.createWorkbook(new File(file_path+"/output.xls"));
//    WritableSheet sheet = workbook.createSheet("First Sheet", 0);
//
//    Label label = new Label(0,0, "001");
//    sheet.addCell(label);
//
//    jxl.write.Number number = new jxl.write.Number(3, 4, 3.1459);
//    sheet.addCell(number);
//    workbook.write();
//    workbook.close(); 

    // 읽기 테스트
    Workbook workbook = Workbook.getWorkbook(new File("c:/myfile.xls"));
    Sheet sheet = workbook.getSheet(0);
    Cell a1 = sheet.getCell(0,0);
    Cell arrayCell[] = new Cell[50];
    for(int i=0; i<arrayCell.length; i++) {
      arrayCell[i] = sheet.getCell(i,0);
    }
    //Cell b2 = sheet.getCell(1,1);
    //Cell c2 = sheet.getCell(2,1);
    String stringa1 = a1.getContents();
    String arrayStr[] = new String[arrayCell.length];
    for(int i=0; i<arrayStr.length; i++) {
      arrayStr[i] = arrayCell[i].getContents();
      System.out.println(arrayStr[i]);
    }
    
    workbook.close(); 
   
    System.out.println(stringa1);
   
  }
}


소스출처 : http://www.okjsp.pe.kr/seq/25170


POI
http://www.javaservice.net/~java/bbs/index.cgi?m=devtip&b=poi
http://jakarta.apache.org/poi/index.html

New Workbook

    HSSFWorkbook wb = new HSSFWorkbook();    FileOutputStream fileOut = new FileOutputStream("workbook.xls");    wb.write(fileOut);    fileOut.close();                    

New Sheet

    HSSFWorkbook wb = new HSSFWorkbook();    HSSFSheet sheet1 = wb.createSheet("new sheet");    HSSFSheet sheet2 = wb.createSheet("second sheet");    FileOutputStream fileOut = new FileOutputStream("workbook.xls");    wb.write(fileOut);    fileOut.close();                    

Creating Cells

    HSSFWorkbook wb = new HSSFWorkbook();    HSSFSheet sheet = wb.createSheet("new sheet");    // Create a row and put some cells in it. Rows are 0 based.    HSSFRow row = sheet.createRow((short)0);    // Create a cell and put a value in it.    HSSFCell cell = row.createCell((short)0);    cell.setCellValue(1);    // Or do it on one line.    row.createCell((short)1).setCellValue(1.2);    row.createCell((short)2).setCellValue("This is a string");    row.createCell((short)3).setCellValue(true);    // Write the output to a file    FileOutputStream fileOut = new FileOutputStream("workbook.xls");    wb.write(fileOut);    fileOut.close();                    

Creating Date Cells

    HSSFWorkbook wb = new HSSFWorkbook();    HSSFSheet sheet = wb.createSheet("new sheet");    // Create a row and put some cells in it. Rows are 0 based.    HSSFRow row = sheet.createRow((short)0);    // Create a cell and put a date value in it.  The first cell is not styled    // as a date.    HSSFCell cell = row.createCell((short)0);    cell.setCellValue(new Date());    // we style the second cell as a date (and time).  It is important to    // create a new cell style from the workbook otherwise you can end up    // modifying the built in style and effecting not only this cell but other cells.    HSSFCellStyle cellStyle = wb.createCellStyle();    cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));    cell = row.createCell((short)1);    cell.setCellValue(new Date());    cell.setCellStyle(cellStyle);    // Write the output to a file    FileOutputStream fileOut = new FileOutputStream("workbook.xls");    wb.write(fileOut);    fileOut.close();                    

Working with different types of cells

    HSSFWorkbook wb = new HSSFWorkbook();    HSSFSheet sheet = wb.createSheet("new sheet");    HSSFRow row = sheet.createRow((short)2);    row.createCell((short) 0).setCellValue(1.1);    row.createCell((short) 1).setCellValue(new Date());    row.createCell((short) 2).setCellValue("a string");    row.createCell((short) 3).setCellValue(true);    row.createCell((short) 4).setCellType(HSSFCell.CELL_TYPE_ERROR);    // Write the output to a file    FileOutputStream fileOut = new FileOutputStream("workbook.xls");    wb.write(fileOut);    fileOut.close();                    

Demonstrates various alignment options

    public static void main(String[] args)            throws IOException    {        HSSFWorkbook wb = new HSSFWorkbook();        HSSFSheet sheet = wb.createSheet("new sheet");        HSSFRow row = sheet.createRow((short) 2);        createCell(wb, row, (short) 0, HSSFCellStyle.ALIGN_CENTER);        createCell(wb, row, (short) 1, HSSFCellStyle.ALIGN_CENTER_SELECTION);        createCell(wb, row, (short) 2, HSSFCellStyle.ALIGN_FILL);        createCell(wb, row, (short) 3, HSSFCellStyle.ALIGN_GENERAL);        createCell(wb, row, (short) 4, HSSFCellStyle.ALIGN_JUSTIFY);        createCell(wb, row, (short) 5, HSSFCellStyle.ALIGN_LEFT);        createCell(wb, row, (short) 6, HSSFCellStyle.ALIGN_RIGHT);        // Write the output to a file        FileOutputStream fileOut = new FileOutputStream("workbook.xls");        wb.write(fileOut);        fileOut.close();    }    /**     * Creates a cell and aligns it a certain way.     *     * @param wb        the workbook     * @param row       the row to create the cell in     * @param column    the column number to create the cell in     * @param align     the alignment for the cell.     */    private static void createCell(HSSFWorkbook wb, HSSFRow row, short column, short align)    {        HSSFCell cell = row.createCell(column);        cell.setCellValue("Align It");        HSSFCellStyle cellStyle = wb.createCellStyle();        cellStyle.setAlignment(align);        cell.setCellStyle(cellStyle);    }                    

Working with borders

    HSSFWorkbook wb = new HSSFWorkbook();    HSSFSheet sheet = wb.createSheet("new sheet");    // Create a row and put some cells in it. Rows are 0 based.    HSSFRow row = sheet.createRow((short) 1);    // Create a cell and put a value in it.    HSSFCell cell = row.createCell((short) 1);    cell.setCellValue(4);    // Style the cell with borders all around.    HSSFCellStyle style = wb.createCellStyle();    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);    style.setBottomBorderColor(HSSFColor.BLACK.index);    style.setBorderLeft(HSSFCellStyle.BORDER_THIN);    style.setLeftBorderColor(HSSFColor.GREEN.index);    style.setBorderRight(HSSFCellStyle.BORDER_THIN);    style.setRightBorderColor(HSSFColor.BLUE.index);    style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM_DASHED);    style.setTopBorderColor(HSSFColor.BLACK.index);    cell.setCellStyle(style);    // Write the output to a file    FileOutputStream fileOut = new FileOutputStream("workbook.xls");    wb.write(fileOut);    fileOut.close();                    

Iterate over rows and cells

Sometimes, you'd like to just iterate over all the rows in a sheet, or all the cells in a row. This is possible with a simple for loop.

Luckily, this is very easy. HSSFRow defines a CellIterator inner class to handle iterating over the cells (get one with a call to row.cellIterator()), and HSSFSheet provides a rowIterator() method to give an iterator over all the rows.

(Unfortunately, due to the broken and backwards-incompatible way that Java 5 foreach loops were implemented, it isn't possible to use them on a codebase that supports Java 1.4, as POI does)

	HSSFSheet sheet = wb.getSheetAt(0);	for (Iterator rit = sheet.rowIterator(); rit.hasNext(); ) {		HSSFRow row = (HSSFRow)rit.next();		for (Iterator cit = row.cellIterator(); cit.hasNext(); ) {			HSSFCell cell = (HSSFCell)cit.next();			// Do something here		}	}				
	HSSFSheet sheet = wb.getSheetAt(0);	for (Iterator<HSSFRow> rit = (Iterator<HSSFRow>)sheet.rowIterator(); rit.hasNext(); ) {		HSSFRow row = rit.next();		for (Iterator<HSSFCell> cit = (Iterator<HSSFCell>)row.cellIterator(); cit.hasNext(); ) {			HSSFCell cell = cit.next();			// Do something here		}	}				

Iterate over rows and cells using Java 1.5 foreach loops - OOXML Branch Only

Sometimes, you'd like to just iterate over all the rows in a sheet, or all the cells in a row. If you are using Java 5 or later, then this is especially handy, as it'll allow the new foreach loop support to work.

Luckily, this is very easy. Both HSSFSheet and HSSFRow implement java.lang.Iterable to allow foreach loops. For HSSFRow this allows access to the CellIterator inner class to handle iterating over the cells, and for HSSFSheet gives the rowIterator() to iterator over all the rows.

	HSSFSheet sheet = wb.getSheetAt(0);	for (HSSFRow row : sheet.rowIterator()) {		for (HSSFCell cell : row.cellIterator()) {			// Do something here		}	}