POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
POI可以操作的文档格式有excel,word,powerpoint等,在此介绍POI操作excel的步骤。关于POI操作其他文档的步骤,大家可以参考其他资料。
首先需要去apache poi的官网上下载poi开发包。我这里使用的版本是3.15
该框架可以对excel样式,单元格格式等等进行修改。今天下午刚入门,这里只简单实现读写操作,基本能实现读写业务,往后深入再继续完善。
为了可读性,删除捕获异常代码,报异常的话,直接添加即可。
完整代码如下:
package poidemo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
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.WorkbookFactory;
import org.apache.poi.ss.util.CellReference;
/**
* 读写excel工具类
* @author Brazen
*
*/
public class poiReadUtil {
public static void main(String[] args) {
//filename();
read();
write();
}
/**
* 获取所有文件名并过滤
*/
public static void filename(){
File file = new File("/Users/Brazen/Desktop/ScanDemoTest");
String [] fileName = file.list(new FilenameFilter(){
@Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
return name.endsWith(".gradle");
}
});
for(String name:fileName){
System.out.println(name);
}
}
/**
* 使用poi框架,读取所有数据。
*
*/
public static void read(){
Workbook wb = WorkbookFactory.create(new FileInputStream("/Users/Brazen/Desktop/test.xlsx"));
Sheet sheet = wb.getSheetAt(0);//第一张表
int rowNum = sheet.getLastRowNum()+1;
int columnNum = sheet.getRow(0).getLastCellNum();
System.out.println("行数"+rowNum);
System.out.println("列数"+columnNum);
//存储数据
for (Row row:sheet) {
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.print(cell.getRichStringCellValue().getString()+",");
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.print(cell.getDateCellValue()+",");
} else {
System.out.print(cell.getNumericCellValue()+",");
}
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue()+",");
break;
case Cell.CELL_TYPE_FORMULA:
System.out.print(cell.getCellFormula()+",");
break;
default:
System.out.print(",");
}
}
System.out.println("");
}
}
public static void write(){
//创建excel工作簿
Workbook wb = new HSSFWorkbook();
//创建第一个sheet(页),命名为 new sheet
Sheet sheet = wb.createSheet("new sheet");
//简单输出100行20列。
for(int i =0;i<100;i++){
Row row = sheet.createRow(i);
for(int j=0;j<20;j++){
row.createCell(j).setCellValue(""+i+":"+j);
}
}
//创建一个文件
FileOutputStream fileOut= new FileOutputStream("/Users/Brazen/Desktop/write.xls");
// 把上面创建的工作簿输出到文件中
wb.write(fileOut);
//关闭输出流
fileOut.close();
}
}