excel工业级读取工具类(代码片段)

悟能的师兄 悟能的师兄     2022-12-03     248

关键词:

最近在做一个自动化匹配快速导入功能,对excel表格导入的一些问题发一个工业级的读取发工具类


import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;


/**
 * Excel相关处理
 *
 * @author HUAWEI
 */
public class ExcelMaterialExtUtil 
    private static final Logger logger = LoggerFactory.getLogger(ExcelMaterialExtUtil.class);

    /**
     * 读取excel文件
     * @param sheetIndex    sheet页下标:从0开始
     * @param startReadLine 开始读取的行:从0开始
     * @param tailLine      去除最后读取的行
     */
    private static void readExcel(Workbook wb, int sheetIndex, int startReadLine, int tailLine) 
        Sheet sheet = wb.getSheetAt(sheetIndex);
        Row row = null;
        for (int i = startReadLine; i < sheet.getLastRowNum() - tailLine + 1; i++) 
            row = sheet.getRow(i);
            for (Cell c : row) 
                boolean isMerge = isMergedRegion(sheet, i, c.getColumnIndex());
                // 判断是否具有合并单元格
                if (isMerge) 
                    String rs = getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
                    logger.info(rs + "");
                 else 
                    logger.info(getCellValue(c) + "");
                
            
        
    

    /**
     * 获取合并单元格的值
     */
    public static String getMergedRegionValue(Sheet 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) 
                    Row fRow = sheet.getRow(firstRow);
                    Cell fCell = fRow.getCell(firstColumn);
                    return getCellValue(fCell);
                
            
        
        return null;
    

    /**
     * 判断合并了行
     */
    private static boolean isMergedRow(Sheet 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;
    

    /**
     * 判断指定的单元格是否是合并单元格
     * @param row    行下标
     * @param column 列下标
     */
    public static boolean isMergedRegion(Sheet 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;
    

    /**
     * 判断sheet页中是否含有合并单元格
     */
    private static boolean hasMerged(Sheet sheet) 
        return sheet.getNumMergedRegions() > 0 ? true : false;
    

    /**
     * 合并单元格
     * @param firstRow 开始行
     * @param lastRow  结束行
     * @param firstCol 开始列
     * @param lastCol  结束列
     */
    private static void mergeRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) 
        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
    

    /**
     * 获得excel 单元格的值
     * @param cell
     * @return
     */
    public static String getCellValue(Cell cell) 
        if (cell == null) return "";

        if (cell.getCellType() == CellType.STRING) 
            return cell.getStringCellValue();
        
        if (cell.getCellType() == CellType.BOOLEAN) 
            return String.valueOf(cell.getBooleanCellValue());
        
        if (cell.getCellType() == CellType.FORMULA) 
            return formulaFormat(cell) ;
        
        if (cell.getCellType() == CellType.NUMERIC) 
            Double numericCellValue = cell.getNumericCellValue() ;
            if( numericCellValue != null && numericCellValue%1.0==0 )
                return Integer.toString( numericCellValue.intValue() );
            
            return String.valueOf( numericCellValue );
        
        if (cell.getCellType() == CellType.ERROR) 
            return String.valueOf(cell.getErrorCellValue());
        
        return "";
    

    /****
     * CellType.FORMULA 数据的处理
     * @param cell
     * @return
     */
    public static String formulaFormat( Cell cell )
        String cellValue = "" ;
        switch (cell.getCachedFormulaResultType()) 
            case STRING:
                cellValue = cell.getStringCellValue();
                break;
            case NUMERIC:
                NumberFormat nf = NumberFormat.getInstance();
                nf.setGroupingUsed(false);
                cellValue = String.valueOf(nf.format(cell.getNumericCellValue()));
                break;
            case BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            default:
                cellValue = cell.getCellFormula();
        
        return cellValue ;
    

1.javapoi读取写入excel(包括样式)的工具类utils(代码片段)

在工作中经常会遇到操作excel的需求,对于格式简单、统一的excel可以选择EasyExcel来实现功能,很简单方便;而对于复杂的excel文件,如有各式各样的合并单元格、表头不固定、行列跟随业务数据动态变化……格式... 查看详情

poi对excel进行读取操作,工具类,便于操作数据(代码片段)

一:首先POI对Excel操作进行了一系列的封装,导入,导出Excel这里借助于POI提供的jar包项目当中导入POI提供的Jar包,这里使用Maven管理 进行导入jar包? <!--https://mvnrepository.com/artifact/org.apache.poi/poi--><dependency><groupId... 查看详情

导出excel工具类(代码片段)

导出Excel的工具方法,主要是生成excel文件:publicstaticvoidwriteFailureReasonToExcelFile(List<FailureReasonResponseEntity>queryAllFailureReasonCountList,Stringpath)try//创建一个工作簿excel文件XSSFWorkbookworkbook=newXS 查看详情

excel工具类(代码片段)

importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.lang.reflect.Field;im 查看详情

excel通用类工具(代码片段)

...个类就可以了;本篇所涉及的项目是在上一篇Excel通用类工具(一)的项目代码上进行的二次添加;正文新添加一个类新添加一个注解类ExcelName,完整代码如下:importjava.lang.annotati 查看详情

csvfileutil读取写入csv文件简单工具类(代码片段)

参考github大神源码总结一下最简单的工具类记录一下/***@descriptionCSV文件读取和输出工具类.<br/>*@authormichael*@date2019/05/16*@versionCopyright(c)2019,[email protected]AllRightsReserved.*/publicclassCSVFileUtilprivatesta 查看详情

配置简单功能强大的excel工具类搞定excel导入导出工具类(代码片段)

对于J2EE项目导入导出Excel是最普通和实用功能,本工具类使用步骤简单,功能强大,只需要对实体类进行简单的注解就能实现导入导出功能,导入导出操作的都是实体对象.请看一下这个类都有哪些功能:?????1.实体属性配置了注解就能... 查看详情

工具类excel导出那些事儿(代码片段)

接上一篇博客,继续介绍双标题导出./***双标题excel导出*@paramresponse*@paramfileName文件名*@paramsheetNamesheet页名*@paramfirstTitle第一行表头标题*@paramtitle第二行标题*@paramcontent每一列对应值*@paramlist单元格下拉选项(可... 查看详情

java常用工具类——excel操作工具(代码片段)

importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.ss.usermodel.*;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOE 查看详情

java常用工具类——文件读取的操作类(代码片段)

定义常用的文件类型publicclassFileType/***文件头类型*/publicstaticfinalStringXML_FILE="text/xml;charset=UTF-8";publicstaticfinalStringPDF_FILE="application/pdf";publicstaticfinalStringPDG_FILE="application/x-png";p 查看详情

原创poi操作excel导入导出工具类excelutil(代码片段)

...,敬请谅解。主要使用ApachePOI进行Excel的导入、导出使用读取Excel中的数据原始数据如下:方法:publicstaticList<List<String>>readFile(InputStreamins,intheadRowNum)throwsException使用方式:StringfilePath="excel文件路径";Filefile=newFile(f... 查看详情

properties文件读取工具类(代码片段)

...erties文件中,根据不同的key加载不同的数据,所以就会有读取properties文件的东西,这篇文章仅为了以后copy方便写的。1.添加依赖:<!--https://mvnrepository.com/artifact/commons-configuration/commons-configuration--><de 查看详情

读取excel还用poi?试试这款开源工具(代码片段)

写在前面Java后端程序员应该会遇到读取Excel信息到DB等相关需求,脑海中可能突然间想起ApachePOI这个技术解决方案,但是当Excel的数据量非常大的时候,你也许发现,POI是将整个Excel的内容全部读出来放入到内存中,所以内存消耗... 查看详情

java读取.txt文件工具类fileutiles(代码片段)

publicclassFileUtilsprivatestaticfinalStringENCODING="UTF-8";//编码方式/***获取文件的行**@paramfileName*文件名称*@returnList<String>*/publicstaticStringgetContentByLine(StringfileName)StringBufferlines=newS 查看详情

java-properties文件读取工具类(代码片段)

1importorg.apache.commons.configuration.ConfigurationException;2importorg.apache.commons.configuration.PropertiesConfiguration;34importcom.alibaba.fastjson.JSON;5importcom.alibaba.fastjson.JSONObject; 查看详情

java-excel工具类(easypoi)(代码片段)

excel工具类EasyPoi1导入依赖<!--EasyPoiUtil导入依赖--><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base</artifactId><version>4.1.0</version></d 查看详情

四easyexcel实现excel读写,封装工具类(代码片段)

...项目中的使用,将对Excel文件的读写操作,封装成工具类。一、EasyExcel实现Excel读写,封装工具类1.1、后端代码ExcelUtil工具类,完成读写操作packagecom.deewin.aftermarket.admin.utils;importcn.hutool.core.convert.Convert;importcom.alibaba... 查看详情

四easyexcel实现excel读写,封装工具类(代码片段)

...项目中的使用,将对Excel文件的读写操作,封装成工具类。一、EasyExcel实现Excel读写,封装工具类1.1、后端代码ExcelUtil工具类,完成读写操作packagecom.deewin.aftermarket.admin.utils;importcn.hutool.core.convert.Convert;importcom.alibaba... 查看详情