Read excel file using poi

Copyright: https://blog.csdn.net/xichengqc/article/details/90443773

Note: The file format is read xls, if xlsx format file, you can right themselves by excel file → Save As and change if the format
guide package

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>
package com.jd.jrmserver.base.test;

import org.apache.poi.hssf.usermodel.*;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * 读取上篇中的xls文件的内容,并打印出来
 *
 * @author Administrator
 */
public class ExcelTest {

    /**
     * 读取一个excel文件的内容
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        //extractor();
        readTable();
    }


    //通过对单元格遍历的形式来获取信息 ,这里要判断单元格的类型才可以取出值
    public static void readTable() throws Exception {
        InputStream ips = new FileInputStream("C:\\Users\\liubin52\\Desktop\\test.xls");
        HSSFWorkbook wb = new HSSFWorkbook(ips);
        HSSFSheet sheet = wb.getSheetAt(0);
        for (Iterator ite = sheet.rowIterator(); ite.hasNext(); ) {
            HSSFRow row = (HSSFRow) ite.next();
            System.out.println();
            for (Iterator itet = row.cellIterator(); itet.hasNext(); ) {
                HSSFCell cell = (HSSFCell) itet.next();
                switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_BOOLEAN:
                        //得到Boolean对象的方法
                        System.out.print(cell.getBooleanCellValue() + " ");
                        break;
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        //先看是否是日期格式
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            //读取日期格式
                            System.out.print(cell.getDateCellValue() + " ");
                        } else {
                            //读取数字
                            System.out.print(cell.getNumericCellValue() + " ");
                        }
                        break;
                    case HSSFCell.CELL_TYPE_FORMULA:
                        //读取公式
                        System.out.print(cell.getCellFormula() + " ");
                        break;
                    case HSSFCell.CELL_TYPE_STRING:
                        //读取String
                        System.out.print(cell.getRichStringCellValue().toString() + " ");
                        break;
                }
            }
        }
    }

}

Guess you like

Origin blog.csdn.net/xichengqc/article/details/90443773