• HSSFWorkbook类



要生成一个Workbook,需要用到HSSFWorkbook类文件。构造器如下:

POI--HSSFWorkbook类-LMLPHP



现在我们使用2种方式来获得一个Workbook对象。

  • 1,创建excel表

HSSFWorkbook workbook = new HSSFWorkbook()。

保存操作用「HSSFWorkbook」类的「write」方法:参数是作为保存对象的输出流对象「OutputStream」。

package linkin;

import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class Linkin
{
public static void main(String[] args)
{
HSSFWorkbook workbook = new HSSFWorkbook();//创建一个空白的workbook FileOutputStream out = null;
try
{
out = new FileOutputStream("sample.xls");
//fileOut= new FileOutputStream("c:\\workbook.xls");
//fileOut= new FileOutputStream("c:/workbook.xls");
workbook.write(out);//调用HSSFWorkbook类的write方法写入到输出流
System.out.println("OK");
}
catch (IOException e)
{
System.out.println(e.toString());
}
finally
{
try
{
out.close();
}
catch (IOException e)
{
System.out.println(e.toString());
}
} } }
  • 2,POIFSFileSystem类定义

「POIFSFileSystem」类对象可以把Excel文件作为数据流来进行传入传出。这里介绍下POIFSFileSystem类,这个类是专门用来读取excel表格的。他有如下2个构造器:

POI--HSSFWorkbook类-LMLPHP



以下代码演示如何通过POIFSFileSystem读取Excel文件:

package linkin;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; public class Linkin
{
public static void main(String[] args)
{
FileInputStream in = null;
HSSFWorkbook workbook = null; try
{
in = new FileInputStream("sample1.xls");//将excel文件转为输入流
POIFSFileSystem fs = new POIFSFileSystem(in);//构建POIFSFileSystem类对象,用输入流构建
workbook = new HSSFWorkbook(fs);//创建个workbook,根据POIFSFileSystem对象
System.out.println("OK");
}
catch (IOException e)
{
System.out.println(e.toString());
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
System.out.println(e.toString());
}
} FileOutputStream out = null;
try
{
out = new FileOutputStream("sample2.xls");
workbook.write(out);
System.out.println("OK");
}
catch (IOException e)
{
System.out.println(e.toString());
}
finally
{
try
{
out.close();
}
catch (IOException e)
{
System.out.println(e.toString());
}
} } }
04-25 13:48