POI对Excel操作——java读取Excel数据

在上篇博文POI对Excel操作——java保存数据到Excel我们介绍了java poi创建数据保存到Excel文件,本篇博文我将介绍如何读取Excel中的数据。下面看java代码:

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;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadExcel {

    public static void main(String[] srgs){
        String filePath = "F:\\d.xls";
        HSSFWorkbook wb = null;
        POIFSFileSystem fs = null;
        try {
            fs = new POIFSFileSystem(new FileInputStream(new File(filePath)));
            wb = new HSSFWorkbook(fs);
        } catch (IOException e) {

        }

        HSSFSheet sheet = wb.getSheetAt(0);
        System.out.println("excel共有数据:" + sheet.getLastRowNum());
        for(int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++){
            HSSFRow row = sheet.getRow(rowNum);
            System.out.print("第" + rowNum + "行数据:");
            for (int cellNum = row.getFirstCellNum() ; cellNum < row.getLastCellNum(); cellNum++) {
                Cell cell = row.getCell(cellNum);
                System.out.print(cell.getStringCellValue() + "   ");
            }
            System.out.println();
        }
    }
}

你可能感兴趣的:(文件操作)