zoukankan      html  css  js  c++  java
  • POI原生导入读取EXCEL

    好久没用 最近项目有冲突 所以又用到了这个 

    谁知道以后还会不会用 先记下来吧 直接扔项目里 调方法就OK 了。

    记录一下。。。。不想再写类似这样的东西了 


    import org.apache.poi.hssf.usermodel.*;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;

    public class ReadExcelUtil {
         private POIFSFileSystem fs;
            private HSSFWorkbook wb;
            private HSSFSheet sheet;
            private HSSFRow row;

            /**
             * 读取Excel表格表头的内容
             * @param is
             * @return String 表头内容的数组
             */
            public String[] readExcelTitle(InputStream is) {
                try {
                    fs = new POIFSFileSystem(is);
                    wb = new HSSFWorkbook(fs);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                sheet = wb.getSheetAt(0);
                //得到首行的row
                row = sheet.getRow(0);
                // 标题总列数
                int colNum = row.getPhysicalNumberOfCells();
                String[] title = new String[colNum];
                for (int i = 0; i < colNum; i++) {
                    title[i] = getCellFormatValue(row.getCell((short) i));
                }
                return title;
            }

            /**
             * 读取Excel数据内容
             * @param is
             * @return Map 包含单元格数据内容的Map对象
             */
            public Map<Integer, String> readExcelContent(InputStream is) {
                Map<Integer, String> content = new HashMap<Integer, String>();
                String str = "";
                String strCell = "";
                try {
                    fs = new POIFSFileSystem(is);
                    wb = new HSSFWorkbook(fs);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                sheet = wb.getSheetAt(0);
                // 得到总行数
                int rowNum = sheet.getLastRowNum();
                //由于第0行和第一行已经合并了  在这里索引从2开始
                row = sheet.getRow(2);
                int colNum = row.getPhysicalNumberOfCells();
                // 正文内容应该从第二行开始,第一行为表头的标题
                for (int i = 2; i <= rowNum; i++) {
                    row = sheet.getRow(i);
                    int j = 0;
                    while (j < colNum) {
                        strCell = getStringCellValue(row.getCell(j));
                        str += strCell + "-";
                       // str +=row.getCell((short) j) + "^";
                        j++;
                    }
                    content.put(i, str);
                    str = "";
                }
                return content;
            }

            /**
             * 获取单元格数据内容为字符串类型的数据
             *
             * @param cell Excel单元格
             * @return String 单元格数据内容
             */
            private String getStringCellValue(HSSFCell cell) {
                String strCell = "";
                switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_STRING:
                        strCell = cell.getStringCellValue();
                        break;
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        strCell = String.valueOf((int)cell.getNumericCellValue());
                        break;
                    case HSSFCell.CELL_TYPE_BOOLEAN:
                        strCell = String.valueOf(cell.getBooleanCellValue());
                        break;
                    case HSSFCell.CELL_TYPE_BLANK:
                        strCell = "";
                        break;
                    default:
                        strCell = "";
                        break;
                }
                if (strCell.equals("") || strCell == null) {
                    return "";
                }
                if (cell == null) {
                    return "";
                }
                return strCell;
            }

            /**
             * 获取单元格数据内容为日期类型的数据
             *
             * @param cell
             *            Excel单元格
             * @return String 单元格数据内容
             */
            private String getDateCellValue(HSSFCell cell) {
                String result = "";
                try {
                    int cellType = cell.getCellType();
                    if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
                        Date date = cell.getDateCellValue();
                        result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1)
                                + "-" + date.getDate();
                    } else if (cellType == HSSFCell.CELL_TYPE_STRING) {
                        String date = getStringCellValue(cell);
                        result = date.replaceAll("[年月]", "-").replace("日", "").trim();
                    } else if (cellType == HSSFCell.CELL_TYPE_BLANK) {
                        result = "";
                    }
                } catch (Exception e) {
                    System.out.println("日期格式不正确!");
                    e.printStackTrace();
                }
                return result;
            }

            /**
             * 根据HSSFCell类型设置数据
             * @param cell
             * @return
             */
            private String getCellFormatValue(HSSFCell cell) {
                String cellvalue = "";
                if (cell != null) {
                    // 判断当前Cell的Type
                    switch (cell.getCellType()) {
                        // 如果当前Cell的Type为NUMERIC
                        case HSSFCell.CELL_TYPE_NUMERIC:
                        case HSSFCell.CELL_TYPE_FORMULA: {
                            // 判断当前的cell是否为Date
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                Date date = cell.getDateCellValue();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                cellvalue = sdf.format(date);
                            }
                            // 如果是纯数字
                            else {
                                // 取得当前Cell的数值
                                cellvalue = String.valueOf(cell.getNumericCellValue());
                            }
                            break;
                        }
                        // 如果当前Cell的Type为STRIN
                        case HSSFCell.CELL_TYPE_STRING:
                            // 取得当前的Cell字符串
                            cellvalue = cell.getRichStringCellValue().getString();
                            break;
                        // 默认的Cell值
                        default:
                            cellvalue = " ";
                    }
                } else {
                    cellvalue = "";
                }
                return cellvalue;

            }

            public static void main(String[] args) {
                try {
                    // 对读取Excel表格标题测试
                    InputStream is = new FileInputStream("d:\test2.xls");
                    ReadExcelUtil excelReader = new ReadExcelUtil();
                    String[] title = excelReader.readExcelTitle(is);
                    System.out.println("获得Excel表格的标题:");
                    for (String s : title) {
                        System.out.print(s + " ");
                    }
                    System.out.println();

                    // 对读取Excel表格内容测试
                    InputStream is2 = new FileInputStream("d:\test2.xls");
                    Map<Integer, String> map = excelReader.readExcelContent(is2);
                    System.out.println("获得Excel表格的内容:");
                    //这里由于xls合并了单元格需要对索引特殊处理
                    for (int i = 2; i <= map.size()+1; i++) {
                        System.out.println(map.get(i));
                    }

                } catch (FileNotFoundException e) {
                    System.out.println("未找到指定路径的文件!");
                    e.printStackTrace();
                }
            }

    }
     
    --------------------- 

  • 相关阅读:
    Python--Requests
    Tensorflow2对GPU内存的分配策略
    Mongodb集成LDAP授权
    监听input输入框实时更新数据
    服务器设置laravel 定时任务调度
    postman---post请求数据类型(转自https://www.cnblogs.com/qican/p/11496820.html)
    webpack
    关于前端加密登陆绕过的渗透思路
    若依(Ruoyi)管理系统后台sql注入+任意文件下载漏洞
    【漏洞复现】YApi接口管理平台远程代码执行漏洞(含批量POC)
  • 原文地址:https://www.cnblogs.com/hyhy904/p/10935211.html
Copyright © 2011-2022 走看看