【Java】Excel解析,文件读取或者上传文件直接读InputStream


import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author : hanfeng
 * @description: Excel parse util.
 * @date : 2020/12/10 21:45
 */
public class ExcelUtils {


    /**
     * logger
     */
    private final static Logger logger = LoggerFactory.getLogger(ExcelUtils.class);

    /**
     * 读取Excel文件
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    private static Workbook read(String filePath) {
        if (filePath == null) {
            return null;
        }
        String ext = filePath.substring(filePath.lastIndexOf("."));
        try {
            FileInputStream inputStream = new FileInputStream(filePath);
            return readFromInputStream(inputStream, ext);
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException", e);
        }
        return null;
    }

    /**
     * 从流中读取,上传文件可以直接获取文件流,无需暂存到服务器上
     *
     * @param inputStream
     * @param ext
     * @return
     */
    private static Workbook readFromInputStream(InputStream inputStream, String ext) {
        try {
            return (!".xls".equals(ext)) ?
                    (".xlsx".equals(ext) ? new XSSFWorkbook(inputStream) : null) : new HSSFWorkbook(inputStream);
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException", e);
        } catch (IOException e) {
            logger.error("IOException", e);
        }
        return null;
    }

    /**
     * 读取Excel内容,返回list,每一行存放一个list
     *
     * @param wb
     * @return
     */
    private static List<List<String>> readExcelContentList(Workbook wb) {
        if (wb != null) {
            List<List<String>> content = new ArrayList<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Sheet sheet = wb.getSheetAt(0);
            Row row = sheet.getRow(0);
            int rowNum = sheet.getLastRowNum();
            int colNum = row.getPhysicalNumberOfCells();
            // 正文内容应该从第二行开始, 第一行为表头的标题
            for (int ri = 1; ri <= rowNum; ri++) {
                row = sheet.getRow(ri);
                int ci = 0;
                List<String> col = new ArrayList<>();
                while (ci < colNum) {
                    Object obj = getCellFormatValue(row.getCell(ci++));
                    obj = (obj instanceof Date) ? simpleDateFormat.format((Date) obj) : obj;
                    col.add((String) obj);
                }
                // if the row is pure blank string, will be filtered,
                // but have the null columns, not all blank, will not destroy the row information, and not be filtered.
                long count = col.stream().filter(StringUtils::isNoneBlank).count();
                Optional.of(col).filter(x -> count > 0).ifPresent(content::add);
            }
            return content;
        }
        return null;
    }


    /**
     * 根据Cell类型设置数据
     *
     * @param cell
     * @return
     */
    private static Object getCellFormatValue(Cell cell) {
        Object cellvalue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:
                case Cell.CELL_TYPE_FORMULA:
                    // 判断当前的cell为Date, 取时间类型;数字则转字符串
                    cellvalue = DateUtil.isCellDateFormatted(cell) ? cell.getDateCellValue() : String.valueOf(cell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:
                    break;
            }
        }
        return cellvalue;
    }

    /**
     * 读取Excel
     *
     * @param filePath Excel文件路径
     * @return
     */
    public static List<List<String>> readExcel(String filePath) {
        Workbook wb = read(filePath);
        return readExcelContentList(wb);
    }

    /**
     * 读取Excel
     *
     * @param inputStream Excel文件流
     * @return
     */
    public static List<List<String>> readExcelFromInputStream(InputStream inputStream, String ext) {
        Workbook workbook = readFromInputStream(inputStream, ext);
        return readExcelContentList(workbook);
    }
}

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用Apache POI库来解析Excel文件。以下是基本的步骤: 1. 添加POI库到项目中,可以通过Maven或手动下载和导入jar包的方式。具体可以参考官方文档:https://poi.apache.org/download.html 2. 通过输入流读取Excel文件,创建一个Workbook对象: ```java FileInputStream inputStream = new FileInputStream(new File("path/to/excel/file.xlsx")); Workbook workbook = new XSSFWorkbook(inputStream); // 或者 HSSFWorkbook(对应xls格式的文件) ``` 3. 获取要解析的Sheet: ```java Sheet sheet = workbook.getSheetAt(0); // 获取第一个Sheet ``` 4. 遍历Sheet中的每一行和每一列,读取单元格的数据: ```java // 遍历行 for (Row row : sheet) { // 遍历列 for (Cell cell : row) { switch (cell.getCellType()) { case STRING: System.out.print(cell.getStringCellValue() + "\t"); break; case NUMERIC: System.out.print(cell.getNumericCellValue() + "\t"); break; case BOOLEAN: System.out.print(cell.getBooleanCellValue() + "\t"); break; default: System.out.print("\t"); } } System.out.println(); } ``` 5. 关闭输入流和Workbook对象: ```java inputStream.close(); workbook.close(); ``` 完整的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; 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.xssf.usermodel.XSSFWorkbook; public class ExcelParser { public static void main(String[] args) throws IOException { FileInputStream inputStream = new FileInputStream(new File("path/to/excel/file.xlsx")); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { switch (cell.getCellType()) { case STRING: System.out.print(cell.getStringCellValue() + "\t"); break; case NUMERIC: System.out.print(cell.getNumericCellValue() + "\t"); break; case BOOLEAN: System.out.print(cell.getBooleanCellValue() + "\t"); break; default: System.out.print("\t"); } } System.out.println(); } inputStream.close(); workbook.close(); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值