原文鏈接:https://blog.csdn.net/class157/article/details/92816169,https://blog.csdn.net/class157/article/details/93237963
package cases;
import org.apache.poi.hssf.usermodel.HSSFCell;
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.*;
import org.testng.annotations.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @description:
* @author: lv
* @time: 2020/5/22 14:21
*/
public class DemoTest {
@Test
public void testPoi()throws IOException {
//建立輸入流
InputStream is = new FileInputStream("D:\\3.xls");
//接受一個輸入流
POIFSFileSystem fs = new POIFSFileSystem(is);
//創建了一個工作簿
HSSFWorkbook wb = new HSSFWorkbook(fs);
//獲取第一個sheet頁
HSSFSheet hssfSheet = wb.getSheetAt(0);
//判斷Sheet是否為空
if (hssfSheet == null) {
return;
}
//遍歷行row
//continue只是終止本次循環,接着還執行后面的循環
for (int rownum = 0; rownum <= hssfSheet.getLastRowNum(); rownum++) {
//獲取到每一行
HSSFRow sheetRow = hssfSheet.getRow(rownum);
if (sheetRow == null) {
continue;
}
//遍歷列cell
for (int cellnum = 0; cellnum <= sheetRow.getLastCellNum(); cellnum++) {
HSSFCell cell = sheetRow.getCell(cellnum);
if (cell == null) {
continue;
}
//獲取單元格的值
System.out.print(" " + getValue(cell));
}
}
}
private static String getValue(HSSFCell hssfCell) {
String cellValue = "";
if(hssfCell == null){
return cellValue;
}
//把數字當成String來讀,避免出現1讀成1.0的情況
hssfCell.setCellType(CellType.STRING);
//hssfCell.getCellType() 獲取當前列的類型
if (hssfCell.getCellType() == CellType.BOOLEAN) {
cellValue = String.valueOf(hssfCell.getBooleanCellValue());
}else if (hssfCell.getCellType() == CellType.NUMERIC) {
cellValue = String.valueOf(hssfCell.getNumericCellValue());
}else if(hssfCell.getCellType() == CellType.STRING){
cellValue = String.valueOf(hssfCell.getStringCellValue());
}else if(hssfCell.getCellType() == CellType.FORMULA){
cellValue = String.valueOf(hssfCell.getCellFormula());
}else if (hssfCell.getCellType() == CellType.BLANK){
cellValue = " ";
}else if(hssfCell.getCellType() == CellType.ERROR){
cellValue = "非法字符";
}else{
cellValue = "未知類型";
}
return cellValue;
}
}
注意點:
調用方式被棄用 cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); 可以使用這個 cell.setCellType(CellType.NUMERIC);
