Java利用POI读Excel

目录

一 POI 相关依赖

二 POI 基本概念

三 POI 读 Excel

3.1 Excel 文件格式

3.2 代码编码 

3.3 执行结果


一 POI 相关依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.16</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.16</version>
</dependency>

二 POI 基本概念

   在 POI 中有如下对应规则:

  • Workbook 代表着一个 Excel 文件。
  • Sheet 代表着 Workbook 中的一个表格。
  • Row 代表 Sheet 中的一行。
  • Cell 代表着一个单元格。

三 POI 读 Excel

3.1 Excel 文件格式

3.2 代码编码 

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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

public class Poi {

    public static void main(String[] args) throws Exception {
        readExcel("你的文件路径");
    }

    /**
     * 从excel中读取数据
     * @param sourceFilePath
     * @return
     * @throws Exception
     */
    public static void readExcel(String sourceFilePath) throws Exception {
        Workbook workbook = null;
        File file = new File(sourceFilePath);
        checkExcelVaild(file);
        workbook = getWorkbok(file);
        /**
         * 设置当前excel中sheet的下标:0开始
         */
        Sheet sheet = workbook.getSheetAt(0);
        //workbook.getNumberOfSheets() 获取Sheet的数量
        //第0行是表名,忽略,从第二行开始读取
        for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
            Row row = sheet.getRow(rowNum);
            if(row.getCell(0).toString().equals("")){
                return;
            }
            for(int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
                Cell cell = row.getCell(cellNum);
                if(cell == null || cell.toString() == null) {
                    continue;
                }
                String value = getCellStringVal(cell).trim();
                if(!"#".equals(value)) {
                    System.out.print(value);
                }
            }
            System.out.println();

        }
    }

    /**
     * 判断文件是否是 excel
     * @throws Exception
     */
    public static void checkExcelVaild(File file) throws Exception {
        if (!file.exists()) {
            throw new Exception("文件不存在");
        }
        if (!(file.isFile() && (file.getName().endsWith("xls") || file.getName().endsWith("xlsx")))) {
            throw new Exception("文件不是Excel");
        }
    }

    /**
     * 判断Excel的版本,获取Workbook
     * @param file
     * @return
     * @throws IOException
     */
    public static Workbook getWorkbok(File file) throws IOException{
        Workbook wb = null;
        FileInputStream in = new FileInputStream(file);
        if(file.getName().endsWith("xls")) {	 //Excel 2003
            wb = new HSSFWorkbook(in);
        } else if(file.getName().endsWith("xlsx")) {	// Excel 2007/2010
            wb = new XSSFWorkbook(in);
        }
        return wb;
    }

    /**
     * 对单元格进行特殊处理
     * @param cell
     * @return
     */
    private static String getCellStringVal(Cell cell) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        CellType cellType = cell.getCellTypeEnum();
        switch (cellType) {
            case STRING:
                return cell.getRichStringCellValue().getString() + "#";
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return fmt.format(cell.getDateCellValue()) + "#";
                } else {
                    cell.setCellType(CellType.STRING);
                    return cell.getRichStringCellValue().getString() + "#";
                }
            case BOOLEAN:
                return cell.getBooleanCellValue() + "#";
            case BLANK:
                return cell.getStringCellValue() + "#";
            case ERROR:
                return "错误#";
            case FORMULA:
                cell.setCellType(CellType.STRING);
                return cell.getRichStringCellValue().getString() + "#";
            default:
                return "#";
        }
    }

}

3.3 执行结果

发布了78 篇原创文章 · 获赞 79 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/jack1liu/article/details/104677653
今日推荐