模块化的POI读取Excel

本文介绍了一种利用Java的Apache POI库读取Excel文件的方法,并提供了完整的代码示例。该方法支持读取多种类型的数据(除了公式),并能进行必填字段验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过POI对excel的读取,支持excel的(除公式以外的其它类型).通过List和Map对Excel读取进行了友好封装,支持excel必选字段判断.一下为代码:

package dointerface;

import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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;

/**
 * @author yansheng
 * @since 2008/6/1
 * @version 0.0.0.1
 *
 */
public class ReadExcel {
  public static void main(String[] args) {
    ParseExcel parse = new ParseExcel();
    try {
      int[] flag = {1, 0, 0, 0};
      int num = 4;
      List> list = parse.parse(num, flag);
      int i=0;
      for (Map map : list) {
        i++;
        System.out.println("第"+ i +"行");
        
        System.out.print(map.get("f1") + " : ");
        System.out.print(map.get("f2") + " : ");
        System.out.print(map.get("f3") + " : ");
        System.out.println(map.get("f4"));
        
      }
    } catch(Exception ex) {
      ex.printStackTrace();
      System.out.println(ex.getMessage());
    }
  }
}

class ParseExcel {
  
  /**
   * 实现excel按首行即标题读取,必须项必须与单元格行数一致
   * @param num int 字段长度
   * @param flag int[] 必选项组,不是必选项为0,是为1
   * @return 返回从Excel中获得的以字段为组的
   *  List<Map<String, String>>
   * @throws Exception 必选项和类型不匹配异常
   */
  public List> parse(int num, int[] flag) throws Exception {
    List<string></string> keyname = new ArrayList<string></string>(); // 存储键值
    ArrayList> list = new ArrayList>();
    
    FileInputStream fis = null;
    fis = new FileInputStream("J://testExcel2.xls");
    POIFSFileSystem pss = new POIFSFileSystem(fis);
    
    HSSFWorkbook workbook = new HSSFWorkbook(pss);
    //读取Sheet
    HSSFSheet sheet = workbook.getSheetAt(0);
    //读取行号
    for (Iterator<hssfrow></hssfrow> rit = sheet.rowIterator(); rit.hasNext(); ) {
      HSSFRow row = (HSSFRow)rit.next();
      if (row.getRowNum() == 0) { //读取第一列字段名
        Iterator<hssfcell></hssfcell> cit = row.cellIterator();
        while (cit.hasNext()) {
          HSSFCell cell = (HSSFCell)cit.next();
          keyname.add(cell.getRichStringCellValue().toString());
        }
      } else {// 遍历cell
        Map map = new HashMap();
        for (int i=0; iString 
   * @param row HSSFRow 行号
   * @param columnNum  HSSFCell 列号
   * @param cell  int 单位格
   * @param flag  int 必填项标志
   * @return 将获得的数据转变为String 
   */
  public String match(HSSFRow row, HSSFCell cell, int columnNum, int flag) throws Exception {
    String str = "";
    int rowNum = row.getRowNum() + 1;
    columnNum++;
    
    // 是否为必填位
    if (flag == 1 &&
        (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK)) {
      throw new Exception(rowNum + "行" + columnNum + "列为必填项");
    } else if(cell != null) {
      if (cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) { // 是否为空型
        str = "";
      }
      else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {// 是否为字符串型
        str = cell.getRichStringCellValue().toString();
      }
      else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {// 是否为数值型
        if (HSSFDateUtil.isCellDateFormatted(cell)) {// 是否为日期型
          str = dateToString(cell.getDateCellValue(), "yyyy-MM-dd");
        }else {// 是否为数值型
          double d = cell.getNumericCellValue();
          if (d-(int)d < Double.MIN_VALUE) { // 是否为int型
            str = Integer.toString((int)d);
          } else { // 是否为double型
            str = Double.toString(cell.getNumericCellValue());
          }
        }
      } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {// 是否为布尔型
        str = Boolean.toString(cell.getBooleanCellValue());
      } else {
        throw new Exception(rowNum + "行" + columnNum + "列数据类型不匹配");
      }
    }
    return str;
  }
  
  /**
   * 将日期型转变为String型的工具方法
   * @param date 日期
   * @param pattern 日期格式
   * @return String的返回值
   */
  public String dateToString(Date date, String pattern) {
    DateFormat format = new SimpleDateFormat(pattern); 
    String str = format.format(date);
    return str;
  }
}

excel表内容

f1f2f3f4
1234
5678
9101112

poi.jar可以到poi.apache.org下载.本例使用poi版本为poi-3.1.jar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值