使用Apache POI 创建和读取MS Excel文档
Apache POI,The POI project consists of APIs for manipulating various file formats based upon Microsoft's OLE 2 Compound Document format using pure Java. In short, you can read and write MS Excel files using Java。经过测试和使用,发觉Apache POI比java Excel API要快很多,并且也更节省资源
下面是一个简单的例子,POItest.java:
import java.text.DecimalFormat; import org.apache.poi.hssf.usermodel.HSSFCell; /** public static String outputFile = "e:\\dest.xls"; public static String fileToBeRead = "e:\\dest.xls"; /** for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { // 新建一输出文件流 } catch (Exception e) { /** DecimalFormat df = new DecimalFormat("#"); try { for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet for (short cellNumOfRow = 0; cellNumOfRow <= aRow if (null != aRow.getCell(cellNumOfRow)) { int cellType = aCell.getCellType(); switch (cellType) { System.out.println(strCell); break; System.out.println(strCell); break; } } } } } } catch (Exception e) { } public static void main(String[] args) { }
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
* 一个Excel文件的层次:Excel文件->工作表->行->单元格 对应到POI中,为:workbook->sheet->row->cell
*
* @author Administrator
*
*/
public class POItest {
* 使用poi创建excel文件
*
*/
public void CreateExcel() {
try {
// 创建新的Excel 工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 在Excel工作簿中建一工作表,其名为缺省值
HSSFSheet sheet = workbook.createSheet("Sheet-0");
// 在索引0的位置创建行(最顶端的行)
HSSFRow row = sheet.createRow((short) i);
// 在索引0的位置创建单元格(左上端)
HSSFCell cell = row.createCell((short) j);
// 定义单元格为字符串类型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
// 在单元格中输入一些内容
// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell
.setCellValue(new HSSFRichTextString("汉字1111111111"
+ j));
}
}
FileOutputStream fOut = new FileOutputStream(outputFile);
// 把相应的Excel 工作簿存盘
workbook.write(fOut);
fOut.flush();
// 操作结束,关闭文件
fOut.close();
System.out.println("文件生成...");
e.printStackTrace();
}
}
*
* 读取excel,遍历各个小格获取其中信息
*/
public void readExcel() {
// 创建对Excel工作簿文件的引用
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
fileToBeRead));
for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
if (null != workbook.getSheetAt(numSheets)) {
HSSFSheet aSheet = workbook.getSheetAt(numSheets);// 获得一个sheet
.getLastRowNum(); rowNumOfSheet++) {
if (null != aSheet.getRow(rowNumOfSheet)) {
HSSFRow aRow = aSheet.getRow(rowNumOfSheet);
.getLastCellNum(); cellNumOfRow++) {
HSSFCell aCell = aRow.getCell(cellNumOfRow);
case 0:// Numeric
String strCell = df.format(aCell
.getNumericCellValue());
case 1:// String
strCell = aCell.getStringCellValue();
default:
// System.out.println("格式不对不读");//其它格式的数据
}
}
e.printStackTrace();
}
POItest poi = new POItest();
poi.CreateExcel();
poi.readExcel();
}