您的位置:首页 > 其它

使用 POI 读取 Excel 表格数据

2016-02-23 17:38 435 查看
参考资料: http://blog.csdn.net/slience_perseverance/article/details/8228157

引入 gradle 依赖:

compile 'org.apache.poi:poi:3.14-beta1'


public static void main(String[] args) {
try {
// 读取文件
InputStream is = new FileInputStream("002.xls");
// 将文件流解析成 POI 文档
POIFSFileSystem fs = new POIFSFileSystem(is);
// 再将 POI 文档解析成 Excel 工作簿
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFRow row = null;
HSSFCell cell = null;
// 得到第 1 个工作簿
HSSFSheet sheet = wb.getSheetAt(0);
// 得到这一行一共有多少列
int totalColumns = sheet.getRow(0).getPhysicalNumberOfCells();
// 得到最后一行的坐标
Integer lastRowNum = sheet.getLastRowNum();
System.out.println("lastRowNum => " + lastRowNum);

List<CorpusWord> corpusBeanList = new ArrayList<>();
CorpusWord corpusBean = null;
String cellValue = null;

// 从第 2 行开始读
for(int i=1;i<=lastRowNum;i++){
row = sheet.getRow(i);
corpusBean = new CorpusWord();
for(int j=0;j<totalColumns;j++){
cell = row.getCell(j);
if(cell!=null){
cellValue = cell.getStringCellValue();
}else {
cellValue = "【没有数据】";
}
if(j==0){
corpusBean.setKey(cellValue);
}
if(j==1){
corpusBean.setAnnotation(cellValue);
}
if(j==2){
corpusBean.setType(cellValue);
corpusBean.setSource("自建");
corpusBean.setPre("");
corpusBean.setSuf("");
}
}
corpusBeanList.add(corpusBean);
}
for(CorpusWord cb:corpusBeanList){
System.out.println(cb);
}
System.out.println("数据条数:" + corpusBeanList.size());

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poi