标签:
1.创建文件流,打开EXCEL文件
FileInputStream excelFile = new FileInputStream(excelPath); XSSFWorkbook workbook = new XSSFWorkbook(excelFile);
2.切换到对应文件名
XSSFSheet excelSheet = workbook.getSheet(sheetName);
3.获取实际行数和列数
int rows = excelSheet.getPhysicalNumberOfRows(); //行数 int cols = excelSheet.getRow(0).getPhysicalNumberOfCells();//列数
4.读取数据
public static String ReadData(XSSFSheet excelSheet, int row, int col){ try{ String CellData= ""; XSSFCell cell = excelSheet.getRow(row).getCell(col); if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){ cell.setCellType(Cell.CELL_TYPE_STRING); CellData = cell.getStringCellValue(); } else if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING){ CellData = cell.getStringCellValue(); } else if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){ CellData = cell.getCellFormula(); } return CellData; }catch(Exception e){ return ""; } }
示例:
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class Excel { public static void main(String[] args) throws IOException { String excelPath = "F:\\login.xlsx"; String sheetName = "001"; try{ FileInputStream excelFile = new FileInputStream(excelPath); XSSFWorkbook workbook = new XSSFWorkbook(excelFile); XSSFSheet excelSheet = workbook.getSheet(sheetName); int row = excelSheet.getPhysicalNumberOfRows(); //行数 int col = excelSheet.getRow(0).getPhysicalNumberOfCells();//列数for(int r = 0; r< row; ++r){ for (int c =0; c < col; ++c){ System.out.print(ReadData(excelSheet, r, c) + ‘ ‘); if(c ==1) System.out.println(); } } workbook.close(); }catch (FileNotFoundException e ){ System.out.println("找不到该文件"); } } public static String ReadData(XSSFSheet excelSheet, int row, int col){ try{ String CellData= ""; XSSFCell cell = excelSheet.getRow(row).getCell(col); if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){ cell.setCellType(Cell.CELL_TYPE_STRING); CellData = cell.getStringCellValue(); } if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING){ CellData = cell.getStringCellValue(); } if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){ CellData = cell.getCellFormula(); } return CellData; }catch(Exception e){ return ""; } } }
输出结果:
标签:
原文地址:http://www.cnblogs.com/hjhsysu/p/5743740.html