Excel读取表格数据并打印出来

前言

因业务需求,博主的代码只读取1列数据并储存到ArrayList中,有别的需求的小伙伴可自行修改。

1、maven依赖


        
            org.apache.poi
            poi-ooxml
            3.9
        
        
            org.apache.poi
            poi
            3.9
        
        
            com.facebook.presto
            presto-jdbc
            0.237
        
    

2、源码

package src.main.util.DownloaddataUtils;

/**
 * Created by l50014840 on 2020/8/6.
 */

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

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 读取Excel
 */
public class ReadExcelUtils {
    private Logger logger = LoggerFactory.getLogger(ReadExcelUtils.class);
    private Workbook wb;
    private Sheet sheet;
    private Row row;

    public ReadExcelUtils(String filepath) {
        if(filepath==null){
            return;
        }
        String ext = filepath.substring(filepath.lastIndexOf("."));
        try {
            InputStream is = new FileInputStream(filepath);
            if(".xls".equals(ext)){
                wb = new HSSFWorkbook(is);
            }else if(".xlsx".equals(ext)){
                wb = new XSSFWorkbook(is);
            }else{
                wb=null;
            }
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException", e);
        } catch (IOException e) {
            logger.error("IOException", e);
        }
    }

    /**
     * 读取Excel表格表头的内容
     *
     * @return String 表头内容的数组
     * @author zengwendong
     */
    public String readExcelTitle() throws Exception{
        if(wb==null){
            throw new Exception("Workbook对象为空!");
        }
        sheet = wb.getSheetAt(0);
        row = sheet.getRow(0);
        // 标题总列数
//        int colNum = row.getPhysicalNumberOfCells();
//        System.out.println("colNum:" + 1);
        String title;
            title = row.getCell(0).getStringCellValue();

        return title;
    }

    /**
     * 读取Excel数据内容
     *
     * @return Map 包含单元格数据内容的Map对象
     * @author zengwendong
     */
    public  ArrayList readExcelContent() throws Exception{
        if(wb==null){
            throw new Exception("Workbook对象为空!");
        }
        Map> content = new HashMap>();

        sheet = wb.getSheetAt(0);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        row = sheet.getRow(0);
        ArrayList arr = new ArrayList<>();
        // 正文内容应该从第二行开始,第一行为表头的标题
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            int j = 0;

            Map cellValue = new HashMap();

            Object obj = getCellFormatValue(row.getCell(j));
            cellValue.put(j, obj);
            arr.add(String.valueOf(cellValue).substring(3,String.valueOf(cellValue).length()-1));
        }

        return arr;
    }

    /**
     *
     * 根据Cell类型设置数据
     *
     * @param cell
     * @return
     * @author zengwendong
     */
    private Object getCellFormatValue(Cell cell) {
        Object cellvalue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:// 如果当前Cell的Type为NUMERIC
                case Cell.CELL_TYPE_FORMULA: {
                    // 判断当前的cell是否为Date
                    if (DateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        cellvalue = date;
                    } else {// 如果是纯数字

                        // 取得当前Cell的数值
                        cellvalue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:// 默认的Cell值
                    cellvalue = "";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }

    public static void main(String[] args) {
        try {
            String filepath = "D:\\temp\\工作簿1.xlsx";
            ReadExcelUtils excelReader = new ReadExcelUtils(filepath);
            // 对读取Excel表格标题测试
			String title = excelReader.readExcelTitle();
			System.out.println("获得Excel表格的标题:");
				System.out.print(title + "\n");
            // 对读取Excel表格内容测试
            ArrayList arr = excelReader.readExcelContent();
            System.out.println("获得Excel表格的内容:");
            System.out.println(arr.toString());
        } catch (FileNotFoundException e) {
            System.out.println("未找到指定路径的文件!");
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(poi,excel,apache,java读取excel)