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

谁知道以后还会不会用 先记下来吧 直接扔项目里 调方法就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();
            }
        }

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

POI原生导入读取EXCEL的更多相关文章

  1. POI 4.0 读取Excel

    ... package POIXLS; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; ...

  2. 使用Apache下poi创建和读取excel文件

    一:使用apache下poi创建excel文档 @Test /* * 使用Apache poi创建excel文件 */ public void testCreateExcel() { // 1:创建一 ...

  3. Java利用POI实现导入导出Excel表格示例代码

    转自:https://www.jb51.net/article/95526.htm 介绍 Jakarta POI 是一套用于访问微软格式文档的Java API.Jakarta POI有很多组件组成,其 ...

  4. Java小知识----POI事件模式读取Excel 2007

    一.知识背景 1.读取excel的方法选择问题 java中读excel中的时间,我们通常用POI去解析,在使用new HSSFWorkbook(NEW FileInputStream(excelFil ...

  5. 结合Poi实现可读取Excel的文件选择对话框

    第一步:ApachePoi的jar包导全,不全会出现异常. 第二步:写就完事了:此例为读取特定模板的excel,仅供参考,根据实际需求改写. package 自建包; import java.awt. ...

  6. java使用poi.3.10读取excel 2003 (xls格式)

    最近在做一个Excel导入数据库的案例,整理文档出来供大家参考. 1.下载 最新的 poi http://poi.apache.org/download.html    2.解压 把相关jar包引进项 ...

  7. 用POI 3.17读取EXCEL数据

    导入jar 包 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</a ...

  8. JAVA导入(读取)Excel中的数据(支持xls与xlsx文件)

    一.导入jar包 poi-3.7.jarpoi-scratchpad-3.7.jarpoi-examples-3.7.jarpoi-ooxml-3.7.jarpoi-ooxml-schemas-3.7 ...

  9. 使用apache的poi实现导入导出excel

    1.jar包:poi-3.14-20160307.jar.poi-ooxml-3.14-20160307.jar 2.导入(本例实现了解析excel生成List): @Override public ...

随机推荐

  1. Fri Jul 28 16:28:52 CST 2017 WARN: Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection mus

    Fri Jul 28 16:28:52 CST 2017 WARN: Establishing SSL connection without server’s identity verificatio ...

  2. i节点,容易被人遗忘的节点

    部分内容转自点击打开链接 点击打开链接 前段时间做了RHCE的一道题,是iSCSi的,后来在挂载的时候说是磁盘被占用.当时资料找了很多结果还是没有找到解决方法.反倒是发现了这个inode,也是关于被占 ...

  3. Java抽象类和接口的区别(好长时间没看这种文章了)

    Java抽象类和接口的区别(好长时间没看这种文章了) abstract class和interface是Java语言中对于抽象类定义进行支持的两种机制,正是由于这两种机制的存在,才赋予了Java强大的 ...

  4. mac系统下mysql5.7.13数据库编码查看和设置

    1.查看编码命令: mysql> show variables like '%character%'; +--------------------------+----------------- ...

  5. 将json文件转换成insert语句的sql文件

    引入是要的maven依赖: <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <depend ...

  6. Ruby自定义打印的字符串

    重要性就不说了,没了这个出点小bug都要查半天. def inspect()     return "要输出的字符串写在这里咯" end         实际代码 #------- ...

  7. bzoj 1907: 树的路径覆盖【贪心+树形dp】

    我是在在做网络流最小路径覆盖的时候找到这道题的 然后发现是个贪心+树形dp \( f[i] \)表示在\( i \)为根的子树中最少有几条链,\( v[i] \) 表示在\( i \)为根的子树中\( ...

  8. java中WGS84坐标(ios)转换BD-09坐标(百度坐标)

    iPhone的GPS定位(CLLocationManager)获得的经纬坐标是基于WGS-84坐标系(世界标准),Google地图使用的是GCJ-02坐标系(中国特色的火星坐标系),百度的经纬坐标在G ...

  9. Qt对象模型之一:信号和槽

    一.信号和槽机制概述 信号槽是 Qt 框架引以为豪的机制之一.所谓信号槽,实际就是观察者模式.当某个事件发生之后,比如,按钮检测到自己被点击了一下,它就会发出一个信号(signal).这种发出是没有目 ...

  10. CF1119F Niyaz and Small Degrees

    题意 给你\(n\)个点的树,边有边权 问使得所有的点度数都小于等于\(x\)的最小删边的代价 \([x \in 0...n-1]\) 题解 首先对于每个\(x\) 可以有一个\(O(nlogn)\) ...