POI之HSSF初探
POI是APACHE出品的一个OFFICE文档操作类库,下面对读取HSSF的一个基本试用。
1、编写测试程序:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
public class Test {
public static void main(String[] args) {
Test t = new Test();
try {
t.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void read() throws IOException {
InputStream input = new FileInputStream("input.xls");
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
for (int r = 0, size = sheet.getPhysicalNumberOfRows(); r < size; r++) {
HSSFRow row = sheet.getRow(r);
for (int c = 0, csize = row.getPhysicalNumberOfCells(); c < csize; c++) {
HSSFCell cell = row.getCell(c);
String value = "";
int type = cell.getCellType();
switch (type) {
case Cell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
value = sdf.format(cell.getDateCellValue());
} else {
value = String.valueOf(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_FORMULA:
value = String.valueOf(cell.getCellFormula());
break;
default:
value = cell.getStringCellValue();
}
System.out.print(c + "=" + value + "| ");
}
System.out.println();
}
}
}
2、准备相关的input.xls(其中公式列添加了乘积公式):
编号 | 部门 | 日期 | 时间 | 数字 | 公式 |
IA100914-006 | 变电一部 | 2010-09-14 | 2010-09-14 17:21:10 | 2 | 4 |
IA100914-005 | 变电一部 | 2010-09-14 | 2010-09-14 17:21:10 | 3 | 6 |
IA100914-004 | 变电一部 | 2010-09-14 | 2010-09-14 17:21:10 | 4 | 8 |
IA100719-001 | 调度中心 | 2010-07-19 | 2010-09-03 17:01:54 | 5 | 10 |
IA100908-016 | 变电一部 | 2010-09-08 | 2010-09-14 16:48:28 | 6 | 12 |
3、得到的输出:
0=编号| 1=部门| 2=日期| 3=时间| 4=数字| 5=公式|
0=IA100914-006| 1=变电一部| 2=2010-09-14 00:00:00| 3=2010-09-14 17:21:10| 4=2.0| 5=PRODUCT(E2,2)|
0=IA100914-005| 1=变电一部| 2=2010-09-14 00:00:00| 3=2010-09-14 17:21:10| 4=3.0| 5=PRODUCT(E3,2)|
0=IA100914-004| 1=变电一部| 2=2010-09-14 00:00:00| 3=2010-09-14 17:21:10| 4=4.0| 5=PRODUCT(E4,2)|
0=IA100719-001| 1=调度中心| 2=2010-07-19 00:00:00| 3=2010-09-03 17:01:54| 4=5.0| 5=PRODUCT(E5,2)|
0=IA100908-016| 1=变电一部| 2=2010-09-08 00:00:00| 3=2010-09-14 16:48:28| 4=6.0| 5=PRODUCT(E6,2)|
4、总体评价:
1)API比较底层,有些繁琐。
2)对于日期时间类型的处理,还有待改进
上一篇: Andrid 永久隐藏导航栏与系统栏
下一篇: 前端(Bootstrop、Flask)