zoukankan      html  css  js  c++  java
  • 使用poi解析Excel文件转化数组形式的集合(List<String[] list)

    1.pom.xml引入jar包

            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>3.17</version>
            </dependency>

    2.解析代码

        /**
         * 解析Excel文件转化数组形式的集合
         * @param in
         * @return
         */
        public static List<String []> excelToList(InputStream in) {
            List<String[]> strings = new ArrayList<>();
            Workbook workbook = null;
            // 当前读取行数-0-based
            int currentRowNum = 0;
            try {
                workbook = WorkbookFactory.create(in);
                Sheet sheet = workbook.getSheetAt(0);
                logger.info("sheet name:" + sheet.getSheetName() + ",last rownum:" + sheet.getLastRowNum());
                for (int x = 0; x <= sheet.getLastRowNum(); x++) {
                    Row row = sheet.getRow(x);
                    currentRowNum = row.getRowNum();
                    StringBuffer sb = new StringBuffer();
                    //设置单元格类型
                    for (int i=0; i< row.getLastCellNum();i++){
                        if(row.getCell(i) != null){
                            row.getCell(i).setCellType(CellType.STRING);
                        }
                        String s = PoiUtils.getStringCellValue(row.getCell(i));
                        sb.append(s);
                        sb.append(",");
                    }
                    strings.add(sb.toString().substring(0, sb.toString().lastIndexOf(",")).split(","));
                }
            }catch (Exception e){
                logger.error("数据读取到第"+currentRowNum+"行时失败");
                e.printStackTrace();
            }finally {
                try {
                    if (null != workbook) {
                        workbook.close();
                    }
                } catch (Exception e2) {
                }
                try {
                    if (null != in) {
                        in.close();
                    }
                } catch (Exception e2) {
                }
            }
            return strings;
        }
  • 相关阅读:
    How to extract msu/msp/msi/exe files from the command line
    Windbg and resources leaks in .NET applications 资源汇总
    [c# 20问] 3.String和string的区别
    [c# 20问] 2.如何转换XML文件
    [c# 20问] 1. 何时使用class与struct
    安装配置BITS上传服务
    The J-Link hardware debugging Eclipse plug-in
    swift material
    SCLButton
    ChatCell
  • 原文地址:https://www.cnblogs.com/xianshen/p/13094755.html
Copyright © 2011-2022 走看看