首页 > 其他分享 >XSSFWorkbook读取合并单元格中的数据

XSSFWorkbook读取合并单元格中的数据

时间:2023-06-15 09:46:21浏览次数:31  
标签:gradeName sheet 读取 row 单元格 cell null XSSFWorkbook String

@Service
public class AppInfoUploadServiceImpl implements AppInfoUploadService {
    @Autowired
    private AppInfoMapper appInfoMapper;
    @Autowired
    private CommonMapper commonMapper;
    @Override
    public void uploadAppInfo(MultipartFile file) {
        LogUtil.info("处理app信息数据...");
        String originalFilename = file.getOriginalFilename();
        if (!originalFilename.endsWith("xlsx"))
        {
            throw new BizException(FailedStatusEnum.MUST_EXCEL_FILE, "originalFilename:" + originalFilename);
        }
        XSSFWorkbook xwb = null;
        try
        {
            List<AppTypePojo> appTypeList = new ArrayList<AppTypePojo>();
            List<AppPojo> appList = new ArrayList<AppPojo>();
            // 读取excel工作簿
            xwb = new XSSFWorkbook(file.getInputStream());
            // 读取excel的词库页
            XSSFSheet sheet = xwb.getSheet("Sheet1");
            Integer sellpointId=null;
            String gradeName = null;
            String subjectName = null;
            String typeName = null;
            String studyProblem = null;
            String scenePic = null;
            String mainAppName = null;
            String mainAppPackageName = null;
            String mainAppIntroduction = null;
            String otherAppName = null;
            String otherAppIntroduction = null;
            String sellpointLatitude = null;
            String addTime=null;
            String lastTime=null;
            AppTypePojo appTypePojo=null;
            AppPojo mainAppPojo=null;
            AppPojo otherAppPojo=null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
            
            for (int i = 1; i <= sheet.getLastRowNum(); i++)
            {
                List<String> otherAppList = new ArrayList<String>();
                XSSFRow row = sheet.getRow(i);
                if (row != null)
                {
                    Boolean mergedRegion1 = isMergedRegion(sheet, i, 1);
                    if (mergedRegion1) {
                         gradeName = getMergedRegionValue(sheet, i, 1);
                    }else{
                        XSSFCell cell = row.getCell(1);
                        if (cell!=null) {
                            gradeName=cell.getStringCellValue();
                        }
                    }
                    if (gradeName!=null) {
                        if (gradeName.contains("一年级")||gradeName.contains("二年级")) {
                            gradeName="一年级#二年级";
                        }else if (gradeName.contains("三年级")||gradeName.contains("四年级")) {
                            gradeName="三年级#四年级";
                        }else if (gradeName.contains("五年级")||gradeName.contains("六年级")) {
                            gradeName="五年级#六年级";
                        }
                    }
                    Boolean mergedRegion2 = isMergedRegion(sheet, i, 2);
                    if (mergedRegion2) {
                        subjectName = getMergedRegionValue(sheet, i, 2);
                    }else{
                        XSSFCell cell = row.getCell(2);
                        if (cell!=null) {
                            subjectName=cell.getStringCellValue();
                        }
                    }
                    
                    Boolean mergedRegion3 = isMergedRegion(sheet, i, 3);
                    if (mergedRegion3) {
                        typeName = getMergedRegionValue(sheet, i, 3);
                    }else{
                        XSSFCell cell = row.getCell(3);
                        if (cell!=null) {
                            typeName=cell.getStringCellValue();
                        }
                    }
                    
                    Boolean mergedRegion4 = isMergedRegion(sheet, i, 4);
                    if (mergedRegion4) {
                        scenePic = getMergedRegionValue(sheet, i, 4);
                    }else{
                        XSSFCell cell = row.getCell(4);
                        if (cell!=null) {
                            scenePic=cell.getStringCellValue();
                        }
                    }
                    
                    Boolean mergedRegion9 = isMergedRegion(sheet, i, 9);
                    if (mergedRegion9) {
                        studyProblem = getMergedRegionValue(sheet, i, 9);
                    }else{
                        XSSFCell cell = row.getCell(9);
                        if (cell!=null) {
                            studyProblem=cell.getStringCellValue();
                        }
                    }
                    
                    
                    Boolean mergedRegion5 = isMergedRegion(sheet, i, 5);
                    if (mergedRegion5) {
                        mainAppName = getMergedRegionValue(sheet, i, 5);
                    }else{
                        XSSFCell cell = row.getCell(5);
                        if (cell!=null) {
                            mainAppName=cell.getStringCellValue();
                        }
                    }
                    
                    Boolean mergedRegion6 = isMergedRegion(sheet, i, 6);
                    if (mergedRegion6) {
                        mainAppPackageName = getMergedRegionValue(sheet, i, 6);
                    }else{
                        XSSFCell cell = row.getCell(6);
                        if (cell!=null) {
                            mainAppPackageName=cell.getStringCellValue();
                        }
                    }
                    
                    Boolean mergedRegion7 = isMergedRegion(sheet, i, 7);
                    if (mergedRegion7) {
                        mainAppIntroduction = getMergedRegionValue(sheet, i, 7);
                    }else{
                        XSSFCell cell = row.getCell(7);
                        if (cell!=null) {
                            mainAppIntroduction=cell.getStringCellValue();
                        }
                    }
                    
                    Boolean mergedRegion8 = isMergedRegion(sheet, i, 8);
                    if (mergedRegion8) {
                        otherAppName = getMergedRegionValue(sheet, i, 8);
                    }else{
                        XSSFCell cell = row.getCell(8);
                        if (cell!=null) {
                            otherAppName=cell.getStringCellValue();
                        }
                    }
                    Integer typeId=appInfoMapper.selectTypeIdByGnameSnameTname(gradeName,subjectName,typeName);
                    if (typeId==null) {
                        CommonQueryVo commonQueryVo = new CommonQueryVo(CommonConstant.TABLE_NAME_APP_TYPE);
                        CommonQueryVo comm = commonMapper.selectMaxOrderNoBytableName(commonQueryVo);
                        commonQueryVo.setFieldName("type_id");
                        CommonQueryVo comm2 = commonMapper.selectMaxFieldBytableName(commonQueryVo);
                        Integer orderNo = comm.getOrderNo();
                        if (orderNo==null) {
                            orderNo=1;
                        }
                        String maxFieldValue = comm2.getMaxFieldValue();
                        Integer typeIdValue = Integer.valueOf(maxFieldValue);
                        if (typeIdValue==null) {
                            typeIdValue=1;
                        }
                        appTypePojo=new AppTypePojo(typeIdValue+1,gradeName,subjectName,typeName,1,orderNo+1);
                        appInfoMapper.insertAppTypeInfo(appTypePojo);
                        typeId=appTypePojo.getId();
                        appTypeList.add(appTypePojo);
                    }
                    CommonQueryVo commonMainApp = new CommonQueryVo(CommonConstant.TABLE_NAME_APP);
                    CommonQueryVo commMainOrder = commonMapper.selectMaxOrderNoBytableName(commonMainApp);
                    Integer orderNoMain=1;
                    if (commMainOrder!=null) {
                        orderNoMain=commMainOrder.getOrderNo();
                    }
                    mainAppPojo=new AppPojo(typeId,studyProblem,scenePic,mainAppName,mainAppPackageName,mainAppIntroduction,1,1,orderNoMain+1);
                    Date d = new Date();
                    String parseDate = sdf.format(d);
                    Date createTime = sdf.parse(parseDate);
                    mainAppPojo.setCreateTime(createTime);
                    //判断该app信息是否存在
                    Integer isExist=appInfoMapper.selectAppinfoIsExist(mainAppPojo);
                    if (isExist>0) {
                        Integer idMainAPP=appInfoMapper.updateAppInfo(mainAppPojo);
                    }else{
                        Integer idMainAPP=appInfoMapper.insertAppInfo(mainAppPojo);
                    }
                    appList.add(mainAppPojo);
                    System.out.println(mainAppPojo.toString());
                    System.out.println("otherAppName="+otherAppName);
                    if ("".equals(otherAppName)) {
                        System.out.println("otherAppName="+otherAppName);
                    }
                    if (otherAppName!=null&&!"".equals(otherAppName)) {
                        CommonQueryVo commonOtherApp = new CommonQueryVo(CommonConstant.TABLE_NAME_APP);
                        String[] splitOtherApp = otherAppName.split("\n");
                        for (int j = 0; j < splitOtherApp.length; j++) {
                            String[] splitMap = splitOtherApp[j].split(" ");
                            System.out.println("splitMap="+splitMap.toString());
                            String otherAppName2="";
                            String otherAppPackage2="";
                            if (splitMap.length>0) {
                                otherAppName2 = splitMap[0];
                                if (splitMap.length>1) {
                                    otherAppPackage2 = splitMap[1];
                                }
                                CommonQueryVo commOtherOrder = commonMapper.selectMaxOrderNoBytableName(commonMainApp);
                                Integer orderNoOther=1;
                                if (commOtherOrder!=null) {
                                    orderNoOther=commOtherOrder.getOrderNo();
                                }
                                otherAppPojo=new AppPojo(typeId,studyProblem,null,otherAppName2,otherAppPackage2,otherAppIntroduction,0,1,orderNoOther+1);
                                Date dOther = new Date();
                                String parsedOtherDate = sdf.format(dOther);
                                Date createdOtherTime = sdf.parse(parsedOtherDate);
                                otherAppPojo.setCreateTime(createdOtherTime);
                                //判断该app信息是否存在
                                Integer isExistO=appInfoMapper.selectAppinfoIsExist(otherAppPojo);
                                if (isExistO>0) {
                                    Integer idOtherAPP=appInfoMapper.updateAppInfo(otherAppPojo);
                                }else{
                                    Integer idOtherAPP=appInfoMapper.insertAppInfo(otherAppPojo);
                                }
                                appList.add(otherAppPojo);
                            }
                        }
                        System.out.println(otherAppList.toString());
                    }
                }
            }
            LogUtil.info("appTypeList:" + JsonTool.toJson(appTypeList));
            LogUtil.info("appList:" + JsonTool.toJson(appList));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                
                xwb.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        
    }
 
    /**
     * @author 
     * TODO判断是否为合并单元格
     * @method isMergedRegion
     * @param sheet
     * @param row
     * @param column
     * @return
     * @return Boolean
     * @date 
     */
    private Boolean isMergedRegion(XSSFSheet sheet,int row,int column){
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row>=firstRow&&row<=lastRow) {
                if (column>=firstColumn&&column<=lastColumn) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * @author 
     * TODO获取合并单元格的值
     * @method getMergedRegionValue
     * @param sheet
     * @param row
     * @param column
     * @return
     * @return String
     * @date 
     */
    public String getMergedRegionValue(XSSFSheet sheet ,int row , int column){      
        int sheetMergeCount = sheet.getNumMergedRegions();      
              
        for(int i = 0 ; i < sheetMergeCount ; i++){      
            CellRangeAddress ca = sheet.getMergedRegion(i);      
            int firstColumn = ca.getFirstColumn();      
            int lastColumn = ca.getLastColumn();      
            int firstRow = ca.getFirstRow();      
            int lastRow = ca.getLastRow();      
            if(row >= firstRow && row <= lastRow){      
                if(column >= firstColumn && column <= lastColumn){      
                    XSSFRow xRow = sheet.getRow(firstRow);     
                    XSSFCell xCell = xRow.getCell(firstColumn);      
                    return getCellValue(xCell);
                }      
            }      
        }      
        return null ;      
    }
    /**
     * @author 
     * TODO获取单元格的值
     * @method getCellValue
     * @param cell
     * @return
     * @return String
     * @date 
     */
    public String getCellValue(XSSFCell cell){      
        if(cell == null) return "";      
        if(cell.getCellType() == XSSFCell.CELL_TYPE_STRING){      
            return cell.getStringCellValue();      
        }else if(cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN){      
            return String.valueOf(cell.getBooleanCellValue());      
        }else if(cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA){      
            return cell.getCellFormula() ;      
        }else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC){      
            return String.valueOf(cell.getNumericCellValue());      
        }  
        return "";      
    }

 

标签:gradeName,sheet,读取,row,单元格,cell,null,XSSFWorkbook,String
From: https://www.cnblogs.com/zhangyuanmingboke/p/17481965.html

相关文章

  • python读取文件——python读取和保存mat文件
      首先我们谈谈MarkDown编辑器,我感觉些倒是挺方便的,因为用惯了LaTeX,对于MarkDown还是比较容易上手的,但是我发现,MarkDown中有这样几个问题一直没能找到具体的解决方法:图片大小的问题。在LaTeX中我们可以调整图片的大小,以适应整个文本;字体,字号大小的设置。在MarkDown里面标题倒是......
  • poi 读取 excel 总行数 ,总列数 注意事项 lastRowNum 、lastCellNum,起始 行号 lastRowN
    poi读取excel总行数,总列数注意事项lastRowNum、lastCellNumhttps://blog.csdn.net/HaHa_Sir/article/details/127235280        poi读取excel总行数,总列数注意事项lastRowNum、lastCellNum一、概述        1、如下图,有一个4行3列的excel表......
  • NodeJS研究笔记:利用Buffer类的二进制数据读取接口解析ELF文件格式
    javascript作为前端开发语言,自古来对二进制数据的读取解析方面的支持都很薄弱,一般来说,解析二进制数据时,往往是将数据转换成字符串,然后运用各种字符串操作技巧来实现二进制数据的读取。由于NodeJS作为后台服务器开发平台,数理逻辑的设计需求超越javascript作为前端语言时界面UI的设......
  • java开发C语言解释器:数组元素的读取和赋值
    本节技术内容难度较大,请结合视频对代码的讲解和调试来理解本节内容:用java开发编译器一个成熟的编译器或解释器,要能够解析和执行目标语言开发的逻辑复杂的程序代码,我们用java开发的C语言解释器,能够执行用C语言开发的较为复杂的程序时,才称得上是合格的,从本节开始,我们致力于C语言解......
  • 文件读取工具类
    importjava.io.*;/***文件读取工具类*/publicclassFileUtil{/***读取文件内容,作为字符串返回*/publicstaticStringreadFileAsString(StringfilePath)throwsIOException{Filefile=newFile(filePath);if(!file.......
  • JavaCV音视频开发宝典:使用JavaCV读取海康平台或海康网络摄像头sdk回调视频TS码流并解
    《JavaCV音视频开发宝典》专栏目录导航《JavaCV音视频开发宝典》专栏介绍和目录​前言两年前博主写了如何利用JavaCV解析各种h264裸流,《JavaCV音视频开发宝典:使用javacv读取GB28181、海康大华平台和网络摄像头sdk回调视频码流并解析预览图像》,但是随着时间变化,各个厂商sdk也......
  • NET CORE Configuraion 使用详解 获取配置文件参数 读取环境变量、读取配置文件、读取
    NETCOREConfiguraion使用详解获取配置文件参数读取环境变量、读取配置文件、读取Ini配置、读取Xml配置、多源配置读取顺序分析https://blog.csdn.net/qq_32109957/article/details/127998326相关配置<ProjectSdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Ex......
  • Java 利用POI对象 SXSSFWorkbook 导出Excel
    最开始调用的方法是(标记的地方): workbook=newHSSFWorkbook();和workbook=newXSSFWorkbook();这两个方法就是导出Excel的最关键的方法,接下来我来说说这两个方法作用:1.HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,扩展名是.xls;2.XSSFWorkbook:是操作Excel2007的版本......
  • MySQL读取的记录和我想象的不一致
    摘要:并发的事务在运行过程中会出现一些可能引发一致性问题的现象,本篇将详细分析一下。本文分享自华为云社区《MySQL读取的记录和我想象的不一致——事物隔离级别和MVCC》,作者:砖业洋__。事务的特性简介1.1原子性(Atomicity)要么全做,要么全不做,一系列操作都是不可分割的,如果在执......
  • 小灰灰深度学习day9——多线程读取小批量数据(这里运行的时候报错了,目前还不会解决,
    在这里先把代码放上来importtorchimporttimeimportnumpyasnpimporttorchvisionfromtorch.utilsimportdatafromtorchvisionimporttransformsfromd2limporttorchasd2ld2l.use_svg_display()#利用svg显示图片importosos.environ["KMP_DUPLICATE_LIB_OK......