Java读取表格内容

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class excel {

    public static void main(String[] args){
        //适用于Java和JavaEE
        //java从本地读取文件
        //web端上传文件为格式 MultipartFile
        MultipartFile file;
        ReadExcelDevicePart(file);
    }
    public void ReadExcelDevicePart(MultipartFile file) throws Exception {
        String EXCEL_XLS = "xls";
        String EXCEL_XLSX = "xlsx";
        if (file.isEmpty()){
            log.error("文件为空");
            throw new GlobalException("文件为空");
        }
        try {
            //根据路径获取这个操作excel的实例
            Sheet sheet = null;
            Row row = null;
            if (file.getOriginalFilename().endsWith(EXCEL_XLS)) {
                //用于xls文件的读取
                HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
                sheet = wb.getSheetAt(0);
            }
            else
            if (file.getOriginalFilename().endsWith(EXCEL_XLSX)) {
                //用于xlsx文件的读取
                XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
                //根据页面index 获取sheet页
                sheet = wb.getSheetAt(0);
            }
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                Map<String,String> bodymap=new HashMap<>();
                //获取每一行数据
                row = sheet.getRow(i);
                //表中第一列String类型的列,这里最好使用如下的方法。如果使用直接获取String的方法,会发生在表格数据为数字的情况下的异常
                if (row.getCell(0) != null) {
                    Cell cell = row.getCell(0);
                    cell.setCellType(CellType.STRING);
                    System.out.println(cell.getStringCellValue());
                }
                //数字类型的列
                if (row.getCell(1) != null) {//括号中为列数
                    //platformsDevicePartVo.setType((int)row.getCell(1).getNumericCellValue());
                    Cell cell = row.getCell(1);
                    cell.setCellType(CellType.STRING);
                    System.out.println(cell.getStringCellValue().trim());
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("excel读取错误");
        }
    }
}

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值