操作excel文件,从文件中读取数据。

java 代码
  1.   
  2. import org.apache.log4j.*;   
  3. import org.apache.poi.hssf.usermodel.*;   
  4. import org.apache.poi.poifs.filesystem.POIFSFileSystem;   
  5.   
  6. import java.util.*;   
  7. import java.io.*;   
  8. /**  
  9. *  
  10. * <p>Title: POIBean.java</p>  
  11. *  
  12. * <p>Description: 该类用于操作excel文件,从文件中读取数据。</p>  
  13. * @version 1.0  
  14. */  
  15. public class POIUtil   
  16. {   
  17.     //定义日志记录器   
  18.     private static final Logger log = Logger.getLogger(POIUtil.class);   
  19.        
  20.     private static POIUtil poiUtil = null;   
  21.        
  22.     //单例   
  23.     POIUtil()   
  24.     {   
  25.     }   
  26.        
  27.     public static POIUtil getInstance()   
  28.     {   
  29.         if (poiUtil == null)   
  30.         {   
  31.             poiUtil = new POIUtil();   
  32.         }   
  33.         return poiUtil;   
  34.     }   
  35.        
  36.      /*******读取xls表格中的数据********  
  37.      * @param filePath : 文件完整路径名  
  38.      * @param worksheet: 读取的工作表,0为第一张工作表  
  39.      * @param start    : 开始读的行数  
  40.      * @param length   : 读取的列数长度,从第一列开始  
  41.      * @param link     : 连接各个单元格的值  
  42.      * @param maxRows  : 读取的最多行数  
  43.      * @throws IOException  
  44.      */  
  45.     public ArrayList readData(String filePath, int worksheet, int start,   
  46.                               int length, String link, final int maxRows) throws IOException   
  47.     {   
  48.         try  
  49.         {   
  50.             File file = new File(filePath);   
  51.             if (!file.exists())   
  52.             {   
  53.                 log.error("read file failed : " + filePath + " is not exist !");   
  54.                 return null;   
  55.             }   
  56.         }   
  57.         catch (Exception e)   
  58.         {   
  59.             log.error(e.toString());   
  60.             return null;   
  61.         }   
  62.         ArrayList arrayList = new ArrayList();   
  63.         FileInputStream fis = null;   
  64.         try  
  65.         {   
  66.             fis = new FileInputStream(filePath);   
  67.             POIFSFileSystem fs = new POIFSFileSystem(fis);   
  68.             HSSFWorkbook wb = new HSSFWorkbook(fs);   
  69.             HSSFSheet sheet = wb.getSheetAt(worksheet);   
  70.             //不存在worksheet   
  71.             if (sheet == null)   
  72.             {   
  73.                 log.error("can not get the specified sheet at " + worksheet);   
  74.                 return null;   
  75.             }   
  76.             //所有的行数   
  77.             int times = 0;   
  78.             for (int i = start; i <= sheet.getLastRowNum(); i++)   
  79.             {   
  80.                 //用于单元格内容为空时,确定其坐标   
  81.                 String division = "";   
  82.                 //整行数据都不为空时,存储这一行的数据   
  83.                 StringBuffer rowValue = new StringBuffer("");   
  84.                 times++;   
  85.                 //超过读的行数   
  86.                 if (times > maxRows)   
  87.                 {   
  88.                     break;   
  89.                 }   
  90.                 HSSFRow row = sheet.getRow(i);   
  91.                 //行值不为空   
  92.                 if (row != null)   
  93.                 {   
  94.                     //所有的列数   
  95.                     for (int j = 0; j < length; j++)   
  96.                     {   
  97.                         HSSFCell cell = row.getCell((short) j);   
  98.                         if (cell == null)   
  99.                         {   
  100.                             division = "@" + (i + 1) + ":" + (j + 1);   
  101.                             rowValue.append(division);   
  102.                             rowValue.append(link);   
  103.                             log.debug("cell " + (i + 1) + ":" + (j + 1) +   
  104.                                       "is null");   
  105.                             continue;   
  106.                         }   
  107.                         switch (cell.getCellType())   
  108.                         {   
  109.                             //单元格内容是数字   
  110.                             case HSSFCell.CELL_TYPE_NUMERIC:   
  111.                                 rowValue.append(new Double(cell.   
  112.                                         getNumericCellValue()).intValue());   
  113.                                 rowValue.append("@" + (i + 1) + ":" + (j + 1));   
  114.                                 rowValue.append(link);   
  115.                                 break;   
  116.   
  117.                                 //单元格内容是字符串   
  118.                             case HSSFCell.CELL_TYPE_STRING:   
  119.                                 rowValue.append(cell.getStringCellValue());   
  120.                                 rowValue.append("@" + (i + 1) + ":" + (j + 1));   
  121.                                 rowValue.append(link);   
  122.                                 break;   
  123.                             default:   
  124.                                 division = "@" + (i + 1) + ":" + (j + 1);   
  125.                                 rowValue.append(division);   
  126.                                 rowValue.append(link);   
  127.                         }   
  128.                     }   
  129.                     arrayList.add(rowValue.toString());   
  130.                 }   
  131.                 //行值为空,登记位置   
  132.                 else  
  133.                 {   
  134.                     log.debug("row " + (i + 1) + "is null");   
  135.                 }   
  136.             }   
  137.         }   
  138.         catch (IOException e)   
  139.         {   
  140.             log.error(e.toString());   
  141.             throw new IOException("IO Exception was found");   
  142.         }   
  143.         finally  
  144.         {   
  145.             // 关闭流   
  146.             if (fis != null)   
  147.             {   
  148.                 fis.close();   
  149.             }   
  150.         }   
  151.         return arrayList;   
  152.     }   
  153.        
  154.     /**  
  155.      * 对Excel文件进行判断  
  156.      * @param File file  Excel文件  
  157.      * @param sheetNames Sheet的名字  
  158.      * @return boolean  是否是真文件  true 真  false 加  
  159.      */  
  160.     public boolean isFile(File file, String[] sheetNames) throws Exception   
  161.     {   
  162.         //记录日志   
  163.         log.debug("enter getCounts()");   
  164.            
  165.         //参数判断   
  166.         if (file == null || !file.exists() || sheetNames == null || sheetNames.length == 0)   
  167.         {   
  168.             log.error("param is not valid");   
  169.             throw new IllegalArgumentException("param is not valid");   
  170.         }   
  171.            
  172.         //定义流变量   
  173.         POIFSFileSystem fs = null;   
  174.         FileInputStream fis = null;   
  175.         HSSFWorkbook hssfWorkBook = null;   
  176.            
  177.         boolean isValid = false;   
  178.            
  179.         //默认的sheet个数为0   
  180.         int counts = 0;   
  181.         try  
  182.         {   
  183.             //读入文件   
  184.             fis = new FileInputStream(file);   
  185.             fs = new POIFSFileSystem(fis);   
  186.                
  187.             hssfWorkBook = new HSSFWorkbook(fs);   
  188.             counts = hssfWorkBook.getNumberOfSheets();   
  189.                
  190.             //对Sheet的个数进行判断   
  191.             if (counts != sheetNames.length)   
  192.             {   
  193.                 return isValid;    
  194.             }   
  195.                
  196.             String tempSheetName = null;   
  197.                
  198.             //再判断sheet名   
  199.             for (int i = 0; i < counts; i++)   
  200.             {   
  201.                 tempSheetName = hssfWorkBook.getSheetName(i);   
  202.                 if (!tempSheetName.equals(sheetNames[i].trim()))   
  203.                 {   
  204.                     return isValid;   
  205.                 }   
  206.             }   
  207.             isValid = true;   
  208.         }   
  209.         catch(IOException ioe)   
  210.         {   
  211.             log.error(ioe.toString());   
  212.             return isValid;   
  213.         }   
  214.         catch(Exception e)   
  215.         {   
  216.             log.error(e.toString());   
  217.             throw new Exception();   
  218.         }   
  219.         finally  
  220.         {   
  221.             try  
  222.             {   
  223.                 fis.close();   
  224.             }   
  225.             catch(Exception e)   
  226.             {   
  227.                 log.error(e.toString());   
  228.                 return isValid;   
  229.             }   
  230.         }   
  231.            
  232.         return isValid;    
  233.     }   
  234.        
  235.        
  236.        
  237.     //测试   
  238.     public static void main(String[] args)   
  239.     {   
  240.         POIUtil poiUtil = new POIUtil();   
  241.            
  242.         ArrayList list = null;   
  243.         try  
  244.         {   
  245.             list=poiUtil.readData("D:\\task模板.xls",0,0,2,"@@@",3);   
  246.         }   
  247.         catch(IOException ioe)   
  248.         {   
  249.                
  250.         }   
  251.            
  252.         if (list == null)   
  253.         {   
  254.             System.out.println("======================");   
  255.         }   
  256.         else  
  257.         {   
  258.             String temp = null;   
  259.             String[] str = new String[2];   
  260.             String[] tempStr = new String[2];   
  261.                
  262.             for (int i = 0; i < list.size(); i++)   
  263.             {   
  264.                 temp = (String)list.get(i);   
  265.                 System.out.println("========row" + temp);   
  266.                 str = temp.split("@@@");   
  267.                 for (int j = 0; j < str.length; j++)   
  268.                 {   
  269.                     tempStr = str[j].split("@");   
  270.                     System.out.println(tempStr.length);   
  271.                     System.out.println(tempStr[0]);   
  272.                     System.out.println(tempStr[1]);   
  273.                 }   
  274.             }   
  275.         }   
  276.     }   
  277.   
  278. }   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 批量读取Excel文件的数据,可以使用Python的pandas库来实现。 首先,我们需要先安装pandas库。可以通过在命令行运行以下命令来安装: ```python pip install pandas ``` 然后,在Python导入pandas库,并使用read_excel函数来读取Excel文件。该函数可以接受文件路径作为参数,并返回一个DataFrame对象,其包含了Excel文件的数据。 下面是一个示例代码: ```python import pandas as pd # 设置文件路径 file_path = '文件路径/文件名.xlsx' # 读取Excel文件 data = pd.read_excel(file_path) # 打印数据 print(data) ``` 在上面的代码,我们首先通过设置文件路径来指定需要读取的Excel文件的位置。然后,使用pd.read_excel函数来将文件读取为一个DataFrame对象,保存在data变量。最后,可以使用print语句来打印读取到的数据。 需要注意的是,上面的代码仅适用于读取单个Excel文件。如果需要批量读取多个Excel文件的数据,可以将上述代码放在一个循环,对每个文件进行读取。 以上就是使用Python批量读取Excel文件数据的方法。 ### 回答2: 批量读取Excel文件的数据可以通过以下步骤实现。 首先,我们需要导入Python的pandas库,因为pandas提供了read_excel()函数来读取Excel文件。 接下来,我们可以使用glob库来获取需要读取的所有Excel文件的路径。通过使用glob.glob()函数并传入文件路径的通配符,我们可以获取到满足条件的所有文件路径。 然后,我们使用一个循环来遍历每个Excel文件的路径。在循环的每个迭代,我们可以使用read_excel()函数来读取该文件,并将数据存储在一个数据框。 最后,我们可以对每个数据框进行进一步的处理,例如合并数据、筛选数据、计算统计指标等,根据具体需求进行操作。 下面是一个示例代码: ```python import pandas as pd import glob # 获取需要读取的所有Excel文件路径 file_paths = glob.glob("path/to/files/*.xlsx") # 循环读取每个Excel文件的数据 for file_path in file_paths: # 使用read_excel()函数读取Excel文件数据 df = pd.read_excel(file_path) # 对数据进行进一步处理,例如合并数据、筛选数据、计算统计指标等 # ... ``` 以上就是通过Python批量读取Excel文件数据的简单方法。通过这个方法,我们可以快速有效地获取多个Excel文件的数据,并进行相应的处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值