poi操作Excel文档

一.POI简介

Jakarta POI 是apache的子项目,目标是处理ole2对象。
项目站点:http://poi.apache.org/
它提供了一组操纵Windows文档的Java API

目前比较成熟的是HSSF接口,处理MS Excel(97-2002)对象。
它不象我们仅仅是用csv生成的没有格式的可以由Excel转换的东西,
而是真正的Excel对象,你可以控制一些属性如sheet,cell等等。

二、版本
JDK:1.5
POI:3.5
更多实例到项目站点查看:http://poi.apache.org/

package com.vefan.excel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.CellReference;

public class POIForXLS
{
public static void main(String[] args){

}

public void createXLS(){
Workbook wb = new HSSFWorkbook();
try
{
FileOutputStream fileOut = new FileOutputStream("E:\\workspace\\JavaApp\\csv\\workbook.xls");
wb.write(fileOut);
fileOut.close();
} catch (Exception e)
{
e.printStackTrace();
}
}

public void readXLS(String filePath){
/*
Getting the cell contents
To get the contents of a cell, you first need to know what kind of cell it is (asking a string cell for its numeric contents will get you a NumberFormatException for example). So, you will want to switch on the cell's type, and then call the appropriate getter for that cell.

In the code below, we loop over every cell in one sheet, print out the cell's reference (eg A3), and then the cell's contents.
*/
// import org.apache.poi.ss.usermodel.*;
FileInputStream fileIn = null;
try
{
fileIn = new FileInputStream("E:\\workspace\\JavaApp\\csv\\workbook.xls");
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
Workbook wb = null;
try
{
wb = new HSSFWorkbook(fileIn);
} catch (IOException e)
{
e.printStackTrace();
}
Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
System.out.print(cellRef.formatAsString());
System.out.print(" - ");

switch(cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
if(DateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue());
} else {
System.out.println(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
System.out.println(cell.getCellFormula());
break;
default:
System.out.println();
}
}
}

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值