Java poi 读取Excel内容

2 篇文章 0 订阅
1 篇文章 0 订阅

Java poi 读取Excel内容

public class ImportExcelUtil  {
    private final static String excel2003L = ".xls"; // 2003- 版本的excel
    private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel
    private final static String excel2007X = ".xlsm"; // 启用宏模式excel

	public List<Dto> excelToList(InputStream in, String name) throws Exception {
	 Workbook work = getWorkbook(in, fileName);
	 List<Dto> dtoList = new ArrayList();
	 if (null == work) {
            throw new Exception("Workbook is null");
            }
     Sheet sheet = null;
     Row row = null;
     Cell cell = null;
     for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            // 取第一行标题
            row = sheet.getRow(0);
            String title[] = null;
            if (row != null) {
                title = new String[row.getLastCellNum()];
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    title[y] = (String) getCellValue(cell);
                }
            } else {
                continue;
            }
             // 从第一行开始读取
            for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
            	row = sheet.getRow(j);
            	//创建接受对象 实体类根据表格自建创建
            	Dto dto= new Dto();
            	// 遍历所有的列 此处是13列
                    for (int y = row.getFirstCellNum(); y < 13; y++) {
                    	
                    	cell = row.getCell(y);
                        String key = title[y];
                        if (key.equals("姓名") && !getCellValue(cell).equals("")) {
                            dto.setName(getCellValue(cell));
                        }
                      //  ....
                    }
            }
            dtoList.add(dto);
      }
      return dtoList;
	}
    //创建Workbook对象方法
	public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (excel2003L.equals(fileType)) {
            wb = new HSSFWorkbook(inStr); 
        } else if (excel2007U.equals(fileType)) {
            wb = new XSSFWorkbook(inStr); 
        }
        else if(excel2007X.equals(fileType)){
            wb = new XSSFWorkbook(inStr); 
        }
        else {
            throw new Exception("解析的文件格式有误!");
        }
        return wb;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值