梦幻之旅

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 阅读(9906) 评论(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包,楼主忘列了吧  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: