apache出来的开源产品太多了,poi也是其中之一。操作Excel 很方便。
下面写一点简单的例子来演示如何使用poi 读取,写入Excel文件。
poi官方下载地址
http://poi.apache.org/download.html
解压出来的一堆文件,只需要一个jar就可以操作了。其他的还没有研究。
poi-3.9-20121203.jar
package com.javaer.file;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
public class ExcelPoi {
public static void write() throws IOException{
// TODO Auto-generated method stub
FileOutputStream fileOut = new FileOutputStream("/test.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("Worksheet");//创建工作簿
HSSFRow row = worksheet.createRow((short) 0);//一行
HSSFCell cellA1 = row.createCell(0);//新建一个格子
cellA1.setCellValue("姓名");
HSSFCellStyle styleOfCell = workbook.createCellStyle();// 格式。
styleOfCell.setFillForegroundColor(HSSFColor.AQUA.index);
styleOfCell.setFillPattern(HSSFCellStyle.BORDER_THIN);
cellA1.setCellStyle(styleOfCell);
HSSFCell cellB1 = row.createCell(1);
cellB1.setCellValue("年龄");
styleOfCell = workbook.createCellStyle();
styleOfCell.setFillForegroundColor(HSSFColor.AQUA.index);
styleOfCell.setFillPattern(HSSFCellStyle.BORDER_THIN);
cellB1.setCellStyle(styleOfCell);
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
}
public static void read() throws IOException{
FileInputStream iStream = new FileInputStream("/test.xls");
HSSFWorkbook workbook = new HSSFWorkbook(iStream);
HSSFSheet worksheet = workbook.getSheet("Worksheet");
//get first row
HSSFRow row = worksheet.getRow(0);
HSSFCell cellA1 = row.getCell(0);
System.out.println(cellA1.getStringCellValue());
HSSFCell cellA2 = row.getCell(1);
System.out.println(cellA2.getStringCellValue());
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
read();
}
}