POI读取excel文件,读取null值,读取批注

建议大家都多看看官方文档,上面写的很详细,一般在Quick Guide可以快速的学会使用此工具
参考网址:http://poi.apache.org/spreadsheet/quick-guide.html
import java.io.FileInputStream;
import java.io.IOException;

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.xssf.usermodel.XSSFWorkbook;


public class Test {

public void get(String filePath) throws IOException, InvalidFormatException{

//把文件写入工作流中。
FileInputStream inp = new FileInputStream(filePath);
//通过WorkbookFactory创建Workbook
Workbook wb = WorkbookFactory.create(inp);
//获得sheet的数量
int sheetNumber = wb.getNumberOfSheets();
for(int i=0; i<sheetNumber; i++){
//逐个获得sheet标签
Sheet sheet = wb.getSheetAt(i);
//通过sheet读取所有row(行)
for(Row row : sheet){
                        //  Sheet sheet = wb.getSheetAt(0);
                       // for (Row row : sheet) {
                      //for (Cell cell : row) {
                         // Do something here
                       //}
                         //}
                      //上面这种方法在for(Cell cell:row)中直接把null值过滤掉
//通过row获得cell的数量
int cellNumber = row.getLastCellNum();
for(int j=0; j<cellNumber; j++){
Cell cell = null;
cell = row.getCell((short)j);
if(cell==null){
System.out.println("此处为0");
}else{
switch(cell.getCellType()){
case Cell.CELL_TYPE_STRING :
System.out.println(cell.getRichStringCellValue());
if(cell.getCellComment()!=null){
System.out.println(cell.getCellComment().getString().toString());
}
break;
case Cell.CELL_TYPE_NUMERIC :
if(DateUtil.isCellDateFormatted(cell)){
System.out.println(cell.getDateCellValue());
}else{
System.out.println(cell.getNumericCellValue());
}
if(cell.getCellComment()!=null){
System.out.println(cell.getCellComment().getString().toString());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
if(cell.getCellComment()!=null){
System.out.println(cell.getCellComment().getString().toString());
}
break;
case Cell.CELL_TYPE_FORMULA:
System.out.println(cell.getCellFormula());
if(cell.getCellComment()!=null){
System.out.println(cell.getCellComment().getString().toString());
}
break;
default:
System.out.println();
}
}
}
}
}
}



public static void main(String[] args){
Test demo = new Test();
try {

demo.get("E:/123456.xlsx");

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

你可能感兴趣的:(poi,批注)