09-11
19

JAVA读取CSV

首先到该http://ostermiller.org/utils/download.html 地址下载com.Ostermiller.util cvs的jar包。

import java.io.*;
import com.Ostermiller.util.ExcelCSVParser;
import com.Ostermiller.util.LabeledCSVParser;

public class CsvFileParser{    
      
    private LabeledCSVParser csvParser;//csv解析器,对于第一行的表头信息,自动加载为索引关键字    
  
    private int currLineNum = -1;//文件所读到行数    
  
    private String[] currLine = null;//用来存放当前行的数据  
      
  
    /*  
     *  构造函数,  
     *  Param: in InputStream 要解析的信息流  
     *  throws IOException  
     */    
  
    protected CsvFileParser(InputStream in) throws IOException {  
          
            csvParser = new LabeledCSVParser(new ExcelCSVParser(in));  
            currLineNum = csvParser.getLastLineNumber();  
    }
  
    /*  
     * 检查是否还有数据  
     *  
     * return ture 还有一行数据,false 没有数据  
     */  
    public boolean hasMore() throws IOException {  
        currLine = csvParser.getLine();  
        currLineNum = csvParser.getLastLineNumber();  
        if (null == currLine)  
            return false;  
        return true;  
    }    
  
    /*  
     * 返回当前行数据,关键字所指向的数据  
     * param:String filedName 该行的表头  
     * return:String 返回当前行数据,关键字所指向的数据  
     */  
    public String getByFieldName(String fieldName) {  
                  
        return csvParser.getValueByLabel(fieldName);  
    }    
  
    /*  
     * 关闭解析器  
     *  
     *  
     */  
    public void close() throws IOException {  
        csvParser.close();    
  
    }    
  
    /*  
     * 读取当前行数据  
     *  
     *  return String[] 读取当前行数据  
     */  
    public String[] readLine() throws IOException {  
        currLine = csvParser.getLine();    
  
        currLineNum = csvParser.getLastLineNumber();    
  
        return currLine;  
  
  
    }    
  
   public int getCurrLineNum(){    
  
         return currLineNum;    
  
  }    
  
    public static void main(String[] args) throws Exception {    
  
         //创建解析信息流  
        InputStream in=new FileInputStream(new File("C:/address.csv"));    
  
       //实例解析器CsvFileParser    
        CsvFileParser parser=new CsvFileParser(in);    
  
       //读取数据  
        while(parser.hasMore()){  
              
            System.out.print(parser.getByFieldName("姓名")+" ");//time 系表头数据  
            System.out.print(parser.getByFieldName("电子邮件")+" ");  
            System.out.print(parser.getByFieldName("手机")+" ");  
            System.out.print(parser.getByFieldName("固定电话")+" ");  
            System.out.print(parser.getByFieldName("别名")+"");  
            System.out.println("\n");
              
        }  
          
        parser.close();  
          
  
    }    
  
}  


文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: cvs 读取
相关日志:
评论: 0 | 引用: 0 | 查看次数: 675
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭