使用Java上传Excel解析工具类(基于springboot)

上传excel分为.xls和.xlsx两种类型的文件
在这里插入图片描述

pom.xml
<dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.2.0</version>
        </dependency>
excel解析工具类
package com.abke.bi.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
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.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: XXXX
 * @Time: 2020/5/28 0028
 * @Description: 解析excel工具类
 */
@Slf4j
public class ReadExcelUtil {

    /**
     * sheet中总行数
     */
    private int totalRows;

    /**
     * 每一行总单元格数
     */
    private static int totalCells;

    /**
     * read the Excel .xlsx,.xls
     *
     * @param file 上传的excel文件
     * @return
     * @throws IOException
     */
    public List<ArrayList<String>> readExcel(MultipartFile file) {
        if (file == null || ExcelUtil.EMPTY.equals(file.getOriginalFilename().trim())) {
            return null;
        } else {
            String postfix = ExcelUtil.getPostfix(file.getOriginalFilename());
            if (!ExcelUtil.EMPTY.equals(postfix)) {
                if (ExcelUtil.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {
                    return readXls(file);
                } else if (ExcelUtil.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)) {
                    return readXlsx(file);
                } else {
                    return null;
                }
            }
        }
        return null;
    }

    /**
     * read the Excel 2010 .xlsx
     *
     * @param file
     * @return
     * @throws IOException
     */
    @SuppressWarnings("deprecation")
    public List<ArrayList<String>> readXlsx(MultipartFile file) {
        List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
        // IO流读取文件
        InputStream input = null;
        XSSFWorkbook wb = null;
        ArrayList<String> rowList = null;
        ArrayList<String> columeList = null;
        try {
            input = file.getInputStream();
            // 创建文档
            wb = new XSSFWorkbook(input);
            // 读取第一个sheet(页)
            XSSFSheet xssfSheet = wb.getSheetAt(0);
            totalRows = xssfSheet.getLastRowNum();

            // 控制
            if (totalRows > 4999) {
                totalRows = 4999;
            }
            // 获取第一行表头信息
            XSSFRow xssfRow1 = xssfSheet.getRow(0);
            if (xssfRow1 != null) {
                columeList = new ArrayList<String>();
                totalCells = xssfRow1.getLastCellNum();
                // 读取列,从第一列开始
                for (int c = 0; c <= totalCells + 1; c++) {
                    XSSFCell cell = xssfRow1.getCell(c);
                    if (cell == null || "".equals(cell)) {
                        break;
                    }
                    cell.setCellType(CellType.STRING);
                    columeList.add("1");
                }
            }
            // 读取Row,从第1行开始
            for (int rowNum = 0; rowNum <= totalRows; rowNum++) {
                XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                if (xssfRow == null) {
                    break;
                }

                if (xssfRow != null) {
                    rowList = new ArrayList<String>();
                    // 读取列,从第一列开始
                    for (int c = 0; c <= columeList.size() - 1; c++) {
                        XSSFCell cell = xssfRow.getCell(c);
                        if (cell == null || "".equals(cell)) {
                            rowList.add("");
                            continue;
                        }
                        // cell.setCellType(CellType.STRING);
                        rowList.add(ExcelUtil.getXValue(cell).trim());
                    }
                    list.add(rowList);
                }
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    /**
     * read the Excel 2003-2007 .xls
     *
     * @param file
     * @return
     * @throws IOException
     */
    public List<ArrayList<String>> readXls(MultipartFile file) {
        List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
        // IO流读取文件
        InputStream input = null;
        HSSFWorkbook wb = null;
        ArrayList<String> rowList = null;
        ArrayList<String> columeList = null;
        try {
            input = file.getInputStream();
            // 创建文档
            wb = new HSSFWorkbook(input);
            //读取sheet(页)
            HSSFSheet hssfSheet = wb.getSheetAt(0);
            totalRows = hssfSheet.getLastRowNum();

            // 控制excel行数
            if (totalRows > 4999) {
                totalRows = 4999;
            }

            // 获取第一行表头信息数量
            HSSFRow row = hssfSheet.getRow(0);
            totalCells = row.getLastCellNum();
            columeList = new ArrayList<String>();
            for (int i = 0; i <= totalCells + 1; i++) {
                HSSFCell cell = row.getCell(i);
                if (cell == null || "".equals(cell)) {
                    break;
                }
                cell.setCellType(CellType.STRING);
                columeList.add("1");
            }


            //读取Row,从第1行开始
            for (int rowNum = 0; rowNum <= totalRows; rowNum++) {
                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow != null) {
                    rowList = new ArrayList<String>();
                    //读取列,从第一列开始
                    for (short c = 0; c <= columeList.size() - 1; c++) {
                        HSSFCell cell = hssfRow.getCell(c);
                        if (cell == null || "".equals(cell)) {
                            rowList.add("");
                            continue;
                        }
                        // cell.setCellType(CellType.STRING);
                        rowList.add(ExcelUtil.getHValue(cell).trim());

                    }
                    list.add(rowList);
                }
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

ExcelUtil
package com.abke.bi.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author XXX
 * @Date 2020/5/27 22:48
 * @Description Excel文件解析工具类
 */
@Component
@Slf4j
public class ExcelUtil {


    public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
    public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
    public static final String EMPTY = "";
    public static final String POINT = ".";
    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    /**
     * 获得path的后缀名
     *
     * @param path
     * @return
     */
    public static String getPostfix(String path) {
        if (path == null || EMPTY.equals(path.trim())) {
            return EMPTY;
        }
        if (path.contains(POINT)) {
            return path.substring(path.lastIndexOf(POINT) + 1, path.length());
        }
        return EMPTY;
    }

    /**
     * 单元格格式
     *
     * @param hssfCell
     * @return
     */
    public static String getHValue(HSSFCell hssfCell) {
        if (hssfCell.getCellTypeEnum() == CellType.BOOLEAN) {
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellTypeEnum() == CellType.NUMERIC) {
            String cellValue = "";
            if (HSSFDateUtil.isCellDateFormatted(hssfCell)) {
                Date date = HSSFDateUtil.getJavaDate(hssfCell.getNumericCellValue());
                cellValue = sdf.format(date);
            } else {
                DecimalFormat df = new DecimalFormat("#.##");
                cellValue = df.format(hssfCell.getNumericCellValue());
                String strArr = cellValue.substring(cellValue.lastIndexOf(POINT) + 1, cellValue.length());
                if (strArr.equals("00")) {
                    cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
                }
            }
            return cellValue;
        } else {
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }

    /**
     * 单元格格式
     *
     * @param xssfCell
     * @return
     */
    public static String getXValue(XSSFCell xssfCell) {
        if (xssfCell.getCellTypeEnum() == CellType.BOOLEAN) {
            return String.valueOf(xssfCell.getBooleanCellValue());
        } else if (xssfCell.getCellTypeEnum() == CellType.NUMERIC) {
            String cellValue = "";
            if (XSSFDateUtil.isCellDateFormatted(xssfCell)) {
                Date date = XSSFDateUtil.getJavaDate(xssfCell.getNumericCellValue());
                cellValue = sdf.format(date);
            } else {
                DecimalFormat df = new DecimalFormat("#.##");
                cellValue = df.format(xssfCell.getNumericCellValue());
                String strArr = cellValue.substring(cellValue.lastIndexOf(POINT) + 1, cellValue.length());
                if (strArr.equals("00")) {
                    cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
                }
            }
            return cellValue;
        } else {
            return String.valueOf(xssfCell.getStringCellValue());
        }
    }

    /**
     * 自定义xssf日期工具类
     */
    static class XSSFDateUtil extends DateUtil {
        protected static int absoluteDay(Calendar cal, boolean use1904windowing) {
            return DateUtil.absoluteDay(cal, use1904windowing);
        }
    } 
}

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
你好!对于Spring Boot项目中的Excel文件解析入库操作,你可以按照以下步骤来实现: 1. 首先,确保你的项目中已经引入了相关的依赖。你可以在 `pom.xml` 文件中添加以下依赖: ```xml <dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- Apache POI for Excel processing --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> </dependencies> ``` 2. 创建一个用于解析Excel文件的工具类。你可以在这个类中编写解析Excel文件的代码。这里使用 Apache POI 来实现。下面是一个简单的示例代码: ```java import org.apache.poi.ss.usermodel.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ExcelParser { public static List<List<String>> parseExcelFile(MultipartFile file) throws IOException { Workbook workbook = WorkbookFactory.create(file.getInputStream()); Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); List<List<String>> data = new ArrayList<>(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); List<String> rowData = new ArrayList<>(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); String cellValue = ""; switch (cell.getCellType()) { case STRING: cellValue = cell.getStringCellValue(); break; case NUMERIC: cellValue = String.valueOf(cell.getNumericCellValue()); break; // 处理其他类型的单元格,根据需要进行扩展 } rowData.add(cellValue); } data.add(rowData); } workbook.close(); return data; } } ``` 3. 创建一个控制器类,在其中接收Excel文件并调用工具类进行解析和入库操作。这里使用Spring MVC来处理请求和响应。示例代码如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; @RestController @RequestMapping("/api") public class ExcelController { @Autowired private ExcelService excelService; @PostMapping("/upload") public void uploadExcelFile(@RequestParam("file") MultipartFile file) throws IOException { List<List<String>> data = ExcelParser.parseExcelFile(file); excelService.saveData(data); } } ``` 4. 创建一个服务类,在其中实现将解析后的数据存入数据库的逻辑。你可以根据自己的需求选择合适的数据库操作框架(如Spring Data JPA、MyBatis等)。示例代码如下: ```java import org.springframework.stereotype.Service; import java.util.List; @Service public class ExcelService { // 注入你的数据访问层对象 public void saveData(List<List<String>> data) { // 解析并保存数据到数据库 } } ``` 这样,你就完成了Spring Boot项目中Excel文件解析入库的基本操作。你可以根据实际需求进行扩展和修改。希望对你有所帮助!如果你还有其他问题,可以继续提问。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橡皮擦不去的争执

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值