夢幻之旅

          DEBUG - 天道酬勤

             :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            671 隨筆 :: 6 文章 :: 256 評論 :: 0 Trackbacks

           

          package com.common.website.util;

          import java.io.File;
          import java.io.FileInputStream;
          import java.io.IOException;
          import java.io.InputStream;
          import java.text.DecimalFormat;
          import java.util.ArrayList;
          import java.util.List;

          import org.apache.poi.hssf.usermodel.HSSFDateUtil;
          import org.apache.poi.hssf.usermodel.HSSFWorkbook;
          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;

          /**
           * <ul>
           * <li>Title:[POI基礎上的Excel數據讀取工具]</li>
           * <li>Description: [支持Excell2003,Excell2007,自動格式化數值型數據,自動格式化日期型數據]</li>
           * <li>Copyright 2009 RoadWay Co., Ltd.</li>
           * <li>All right reserved.</li>
           * <li>Created by [惠萬鵬] [Jan 20, 2010]</li>
           * <li>Midified by [modifier] [modified time]</li>
           * 
           * <li>所需Jar包列表</li>
           * <li>poi-3.6-20091214.jar</li>
           * <li>poi-contrib-3.6-20091214.jar</li>
           * <li>poi-examples-3.6-20091214.jar</li>
           * <li>poi-ooxml-3.6-20091214.jar</li>
           * <li>poi-ooxml-schemas-3.6-20091214.jar</li>
           * <li>poi-scratchpad-3.6-20091214.jar</li>
           * <li>xmlbeans-2.3.0.jar</li>
           * <ul>
           * 
           * 
          @version 1.0
           
          */

          public class POIExcelUtil
          {
              
          /** 總行數 */
              
          private int totalRows = 0;
              
              
          /** 總列數 */
              
          private int totalCells = 0;
              
              
          /** 構造方法 */
              
          public POIExcelUtil()
              
          {}
              
              
          /**
               * <ul>
               * <li>Description:[根據文件名讀取excel文件]</li>
               * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>
               * <li>Midified by [modifier] [modified time]</li>
               * <ul>
               * 
               * 
          @param fileName
               * 
          @return
               * 
          @throws Exception
               
          */

              
          public List<ArrayList<String>> read(String fileName)
              
          {
                  List
          <ArrayList<String>> dataLst = new ArrayList<ArrayList<String>>();
                  
                  
          /** 檢查文件名是否為空或者是否是Excel格式的文件 */
                  
          if (fileName == null || !fileName.matches("^.+\\.(?i)((xls)|(xlsx))$"))
                  
          {
                      
          return dataLst;
                  }

                  
                  
          boolean isExcel2003 = true;
                  
          /** 對文件的合法性進行驗證 */
                  
          if (fileName.matches("^.+\\.(?i)(xlsx)$"))
                  
          {
                      isExcel2003 
          = false;
                  }

                  
                  
          /** 檢查文件是否存在 */
                  File file 
          = new File(fileName);
                  
          if (file == null || !file.exists())
                  
          {
                      
          return dataLst;
                  }

                  
                  
          try
                  
          {
                      
          /** 調用本類提供的根據流讀取的方法 */
                      dataLst 
          = read(new FileInputStream(file), isExcel2003);
                  }

                  
          catch (Exception ex)
                  
          {
                      ex.printStackTrace();
                  }

                  
                  
          /** 返回最后讀取的結果 */
                  
          return dataLst;
              }

              
              
          /**
               * <ul>
               * <li>Description:[根據流讀取Excel文件]</li>
               * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>
               * <li>Midified by [modifier] [modified time]</li>
               * <ul>
               * 
               * 
          @param inputStream
               * 
          @param isExcel2003
               * 
          @return
               
          */

              
          public List<ArrayList<String>> read(InputStream inputStream,
                      
          boolean isExcel2003)
              
          {
                  List
          <ArrayList<String>> dataLst = null;
                  
          try
                  
          {
                      
          /** 根據版本選擇創建Workbook的方式 */
                      Workbook wb 
          = isExcel2003 ? new HSSFWorkbook(inputStream)
                              : 
          new XSSFWorkbook(inputStream);
                      dataLst 
          = read(wb);
                  }

                  
          catch (IOException e)
                  
          {
                      e.printStackTrace();
                  }

                  
          return dataLst;
              }

              
              
          /**
               * <ul>
               * <li>Description:[得到總行數]</li>
               * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>
               * <li>Midified by [modifier] [modified time]</li>
               * <ul>
               * 
               * 
          @return
               
          */

              
          public int getTotalRows()
              
          {
                  
          return totalRows;
              }

              
              
          /**
               * <ul>
               * <li>Description:[得到總列數]</li>
               * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>
               * <li>Midified by [modifier] [modified time]</li>
               * <ul>
               * 
               * 
          @return
               
          */

              
          public int getTotalCells()
              
          {
                  
          return totalCells;
              }

              
              
          /**
               * <ul>
               * <li>Description:[讀取數據]</li>
               * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>
               * <li>Midified by [modifier] [modified time]</li>
               * <ul>
               * 
               * 
          @param wb
               * 
          @return
               
          */

              
          private List<ArrayList<String>> read(Workbook wb)
              
          {
                  List
          <ArrayList<String>> dataLst = new ArrayList<ArrayList<String>>();
                  
                  
          /** 得到第一個shell */
                  Sheet sheet 
          = wb.getSheetAt(0);
                  
          this.totalRows = sheet.getPhysicalNumberOfRows();
                  
          if (this.totalRows >= 1 && sheet.getRow(0!= null)
                  
          {
                      
          this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
                  }

                  
                  
          /** 循環Excel的行 */
                  
          for (int r = 0; r < this.totalRows; r++)
                  
          {
                      Row row 
          = sheet.getRow(r);
                      
          if (row == null)
                      
          {
                          
          continue;
                      }

                      
                      ArrayList
          <String> rowLst = new ArrayList<String>();
                      
          /** 循環Excel的列 */
                      
          for (short c = 0; c < this.getTotalCells(); c++)
                      
          {
                          Cell cell 
          = row.getCell(c);
                          String cellValue 
          = "";
                          
          if (cell == null)
                          
          {
                              rowLst.add(cellValue);
                              
          continue;
                          }

                          
                          
          /** 處理數字型的,自動去零 */
                          
          if (Cell.CELL_TYPE_NUMERIC == cell.getCellType())
                          
          {
                              
          /** 在excel里,日期也是數字,在此要進行判斷 */
                              
          if (HSSFDateUtil.isCellDateFormatted(cell))
                              
          {
                                  cellValue 
          = DateUtil.get4yMdHms(cell.getDateCellValue());
                              }

                              
          else
                              
          {
                                  cellValue 
          = getRightStr(cell.getNumericCellValue() + "");
                              }

                          }

                          
          /** 處理字符串型 */
                          
          else if (Cell.CELL_TYPE_STRING == cell.getCellType())
                          
          {
                              cellValue 
          = cell.getStringCellValue();
                          }

                          
          /** 處理布爾型 */
                          
          else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType())
                          
          {
                              cellValue 
          = cell.getBooleanCellValue() + "";
                          }

                          
          /** 其它的,非以上幾種數據類型 */
                          
          else
                          
          {
                              cellValue 
          = cell.toString() + "";
                          }

                          
                          rowLst.add(cellValue);
                      }

                      dataLst.add(rowLst);
                  }

                  
          return dataLst;
              }

              
              
          /**
               * <ul>
               * <li>Description:[正確地處理整數后自動加零的情況]</li>
               * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>
               * <li>Midified by [modifier] [modified time]</li>
               * <ul>
               * 
               * 
          @param sNum
               * 
          @return
               
          */

              
          private String getRightStr(String sNum)
              
          {
                  DecimalFormat decimalFormat 
          = new DecimalFormat("#.000000");
                  String resultStr 
          = decimalFormat.format(new Double(sNum));
                  
          if (resultStr.matches("^[-+]?\\d+\\.[0]+$"))
                  
          {
                      resultStr 
          = resultStr.substring(0, resultStr.indexOf("."));
                  }

                  
          return resultStr;
              }

              
              
          /**
               * <ul>
               * <li>Description:[測試main方法]</li>
               * <li>Created by [Huyvanpull] [Jan 20, 2010]</li>
               * <li>Midified by [modifier] [modified time]</li>
               * <ul>
               * 
               * 
          @param args
               * 
          @throws Exception
               
          */

              
          public static void main(String[] args) throws Exception
              
          {
                  List
          <ArrayList<String>> dataLst = new POIExcelUtil()
                          .read(
          "e:/Book1_shao.xls");
                  
          for (ArrayList<String> innerLst : dataLst)
                  
          {
                      StringBuffer rowData 
          = new StringBuffer();
                      
          for (String dataStr : innerLst)
                      
          {
                          rowData.append(
          ",").append(dataStr);
                      }

                      
          if (rowData.length() > 0)
                      
          {
                          System.out.println(rowData.deleteCharAt(
          0).toString());
                      }

                  }

              }

          }
          posted on 2010-01-20 18:25 HUIKK 閱讀(9931) 評論(14)  編輯  收藏 所屬分類: TOOL

          評論

          # re: java 讀取 excel 2003 或 excel 2007 2010-12-15 14:10 張三
          如果一次讀取 300000條數據怎么辦?  回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007 2010-12-31 11:41
          把你的poi包給我發一份。謝謝
          * poi-3.6-20091214.jar
          * poi-contrib-3.6-20091214.jar
          * poi-examples-3.6-20091214.jar
          * poi-ooxml-schemas-3.6-20091214.jar
          * poi-scratchpad-3.6-20091214.jar
          * >xmlbeans-2.3.0.jar  回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007 2010-12-31 11:41
          @張
          我的郵箱123306454@qq.com  回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007 2012-05-28 17:42 haidizhixin
          什么啊,程序不對Workbook wb = isExcel2003 ? new HSSFWorkbook(inputStream)
          : new XSSFWorkbook(inputStream);
            回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007 2012-10-15 18:33 潘洪飛
          DateUtil.get4yMdHms這個方法報錯啊 怎么回事兒啊 下載的是你的jar包 求解釋  回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007 2012-10-15 22:44 惠萬鵬
          public class DateUtil
          {
          /**
          * <ul>
          * <li>Description:[得到當前的時間]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @return
          */
          public static Date getDate()
          {
          Calendar canlendar = Calendar.getInstance();
          return canlendar.getTime();
          }

          /**
          * <ul>
          * <li>Description:[提到指定的millis得到時間]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param millis
          * @return
          */
          public static Date getDate(long millis)
          {
          Calendar canlendar = Calendar.getInstance();
          canlendar.clear();
          canlendar.setTimeInMillis(millis);
          return canlendar.getTime();
          }

          public static long getMillis()
          {
          return Calendar.getInstance().getTimeInMillis();
          }

          /**
          * <ul>
          * <li>Description:[得到指定日期的字符串(yyyy-MM-dd HH:mm:ss.SSS)]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param date
          * @param formate
          * @return
          */
          public static String getDateFormate(Date date, String formate)
          {
          try
          {
          SimpleDateFormat simpleDateFormate = new SimpleDateFormat(formate);
          return simpleDateFormate.format(date);
          }
          catch (Exception e)
          {}
          return "";
          }

          /**
          * <ul>
          * <li>Description:[根據日期得到YYYY-MM-DD HH:MM:SS.SSS格式字符串]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param date
          * @return
          */
          public static String get4yMdHmsS(Date date)
          {
          return DateUtil.getDateFormate(date, "yyyy-MM-dd HH:mm:ss.SSS");
          }

          /**
          * <ul>
          * <li>Description:[根據日期得到YYYY-MM-DD HH:MM:SS格式字符串]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param date
          * @return
          */
          public static String get4yMdHms(Date date)
          {
          return DateUtil.getDateFormate(date, "yyyy-MM-dd HH:mm:ss");
          }

          /**
          * <ul>
          * <li>Description:[根據日期得到YYYY-MM-DD HH:MM格式字符串]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param date
          * @return
          */
          public static String get4yMdHm(Date date)
          {
          return DateUtil.getDateFormate(date, "yyyy-MM-dd HH:mm");
          }

          /**
          * <ul>
          * <li>Description:[根據日期得到YYYY-MM-DD格式字符串]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param date
          * @return
          */
          public static String get4yMd(Date date)
          {
          return DateUtil.getDateFormate(date, "yyyy-MM-dd");
          }

          /**
          * <ul>
          * <li>Description:[把指定字符(yyyy-MM-dd HH:mm:ss.SSS)串轉成Date]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param sDate
          * @return
          */
          public static Date parse4yMdHmsS(String sDate)
          {
          return DateUtil.parseDate(sDate, "yyyy-MM-dd HH:mm:ss.SSS");
          }

          /**
          * <ul>
          * <li>Description:[把指定字符(yyyy-MM-dd HH:mm:ss)串轉成Date]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param sDate
          * @return
          */
          public static Date parse4yMdHms(String sDate)
          {
          return DateUtil.parseDate(sDate, "yyyy-MM-dd HH:mm:ss");
          }

          /**
          * <ul>
          * <li>Description:[把指定字符(yyyy-MM-dd HH:mm)串轉成Date]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param sDate
          * @return
          */
          public static Date parse4yMdHm(String sDate)
          {
          return DateUtil.parseDate(sDate, "yyyy-MM-dd HH:mm");
          }

          /**
          * <ul>
          * <li>Description:[把指定字符(yyyy-MM-dd)串轉成Date]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param sDate
          * @return
          */
          public static Date parse4yMd(String sDate)
          {
          return DateUtil.parseDate(sDate, "yyyy-MM-dd");
          }

          /**
          * <ul>
          * <li>Description:[根據指定格式,把字符串轉成日期]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param sDate
          * @param formate
          * @return
          */
          public static Date parseDate(String sDate, String formate)
          {
          SimpleDateFormat simpleDateFormate = new SimpleDateFormat(formate);
          try
          {
          return simpleDateFormate.parse(sDate);
          }
          catch (ParseException e)
          {
          return null;
          }
          }

          /**
          * <ul>
          * <li>Description:[兩個長整型的時間相差(時間的毫秒數),可以得到指定的毫秒數,秒數,分鐘數,天數]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param minuendTime[被減去的時間]
          * @param subtrahendTime[減去的時間]
          * @param tdatestr[part可選值["D","H","M","S","MS"]
          * @return[minuendTime-subtrahendTime]
          * @return
          */
          public static double getDifTwoTime(Date minuendTime, Date subtrahendTime,
          String tdatestr)
          {
          if (minuendTime == null || subtrahendTime != null)
          {
          return DateUtil.getDifTwoTime(minuendTime.getTime(), subtrahendTime
          .getTime(), tdatestr);
          }
          return 0;
          }

          /**
          * <ul>
          * <li>Description:[兩個長整型的時間相差(時間的毫秒數),可以得到指定的毫秒數,秒數,分鐘數,天數]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param minuendTime[被減去的時間]
          * @param subtrahendTime[減去的時間]
          * @param tdatestr[part可選值["D","H","M","S","MS"]
          * @return[minuendTime-subtrahendTime]
          */
          public static double getDifTwoTime(long minuendTime, long subtrahendTime,
          String tdatestr)
          {
          if (tdatestr == null || tdatestr.equals(""))
          {
          tdatestr = "MS";
          }
          double temp = 1;
          /** 毫秒數 */
          if ("MS".equalsIgnoreCase(tdatestr))
          {
          temp = 1;
          }
          /** 得到秒 */
          if ("S".equalsIgnoreCase(tdatestr))
          {
          temp = 1000;
          }
          /** 得到分 */
          if ("M".equalsIgnoreCase(tdatestr))
          {
          temp = 1000 * 60;
          }
          /** 得到小時 */
          if ("H".equalsIgnoreCase(tdatestr))
          {
          temp = 1000 * 60 * 60;
          }
          /** 得到天 */
          if ("D".equalsIgnoreCase(tdatestr))
          {
          temp = 1000 * 60 * 60 * 24;
          }
          return (minuendTime - subtrahendTime) / temp;
          }

          /**
          * <ul>
          * <li>Description:[從日期中得到指定部分(YYYY/MM/DD/HH/SS/SSS)數字]</li>
          * <li>Created by [Huyvanpull] [Oct 26, 2009]</li>
          * <li>Midified by [modifier] [modified time]</li>
          * <ul>
          *
          * @param date
          * @param part[part可選值["Y","M","D","H","M","S","MS"]
          * @return
          */
          public static int getPartOfTime(Date date, String part)
          {
          Calendar canlendar = Calendar.getInstance();
          canlendar.clear();
          canlendar.setTime(date);
          /** 得到年 */
          if (part.equalsIgnoreCase("Y"))
          {
          return canlendar.get(Calendar.YEAR);
          }
          /** 得到月 */
          if (part.equalsIgnoreCase("M"))
          {
          return canlendar.get(Calendar.MONTH) + 1;
          }
          /** 得到日 */
          if (part.equalsIgnoreCase("D"))
          {
          return canlendar.get(Calendar.DAY_OF_MONTH);
          }
          /** 得到時 */
          if (part.equalsIgnoreCase("H"))
          {
          return canlendar.get(Calendar.HOUR_OF_DAY);
          }
          /** 得到分 */
          if (part.equalsIgnoreCase("M"))
          {
          return canlendar.get(Calendar.MINUTE);
          }
          /** 得到秒 */
          if (part.equalsIgnoreCase("S"))
          {
          return canlendar.get(Calendar.SECOND);
          }
          /** 得到毫秒 */
          if (part.equalsIgnoreCase("MS"))
          {
          return canlendar.get(Calendar.MILLISECOND);
          }
          return -1;
          }
          }  回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007 2012-12-21 12:41 ysc
          能讀2003xls文件,但是讀不了xlsx文件  回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007 2012-12-21 13:58 ysc
          不是程序不對,讀取2003沒問題,讀取2007的話Workbook wb = isExcel2003 ? new HSSFWorkbook(inputStream)
          : new XSSFWorkbook(inputStream) 這一行就會有異常,我覺得不是程序的錯誤,可能是jar包出錯了?? 我也不知道,希望樓主能出面解決一下  回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007 2012-12-21 14:00 惠萬鵬
          沒問題的, 這個是經過測試, 現在項目也在使用.
          你檢查一下你的jar包是否有問題.  回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007 2012-12-21 14:01 惠萬鵬
          加我QQ我給你一個文件.  回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007 2013-05-05 08:42 王忠付
          錯誤: 找不到或無法加載主類,怎么會這樣,jar包倒入沒問題阿!  回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007 2013-05-05 09:14 王忠付
          完全沒問題,eclipse的問題  回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007[未登錄] 2013-08-01 17:31 hi
          有類變量,并發會有問題吧?  回復  更多評論
            

          # re: java 讀取 excel 2003 或 excel 2007 2014-02-10 20:51 水行草
          還需要dom4j這個jar包,樓主忘列了吧  回復  更多評論
            

          主站蜘蛛池模板: 故城县| 文成县| 堆龙德庆县| 金沙县| 晋中市| 天门市| 武汉市| 文安县| 曲阜市| 工布江达县| 化德县| 额济纳旗| 浦江县| 上高县| 峨眉山市| 苍溪县| 西华县| 英山县| 建瓯市| 延寿县| 微博| 镇安县| 渑池县| 马鞍山市| 乌兰浩特市| 大丰市| 盈江县| 禹州市| 视频| 黔西县| 山阴县| 宜宾县| 焉耆| 名山县| 安平县| 龙川县| 贵阳市| 宝坻区| 永吉县| 通河县| 杨浦区|