首页 文章

适用于Java的CSV API [已关闭]

提问于
浏览
155

任何人都可以推荐一个简单的API,它允许我使用读取CSV输入文件,做一些简单的转换,然后编写它 .

一个快速谷歌发现http://flatpack.sourceforge.net/看起来很有希望 .

我只是想在结合这个API之前检查一下其他人在使用什么 .

10 回答

  • 80

    阅读CSV格式的描述让我觉得使用第三方库比自己写的要少:

    维基百科列出了10个或者已知的库:

    我比较了使用某种检查列表列出的库 . OpenCSV对我来说是一个胜利者(YMMV),结果如下:

    + maven
    
    + maven - release version   // had some cryptic issues at _Hudson_ with snapshot references => prefer to be on a safe side
    
    + code examples
    
    + open source   // as in "can hack myself if needed"
    
    + understandable javadoc   // as opposed to eg javadocs of _genjava gj-csv_
    
    + compact API   // YAGNI (note *flatpack* seems to have much richer API than OpenCSV)
    
    - reference to specification used   // I really like it when people can explain what they're doing
    
    - reference to _RFC 4180_ support   // would qualify as simplest form of specification to me
    
    - releases changelog   // absence is quite a pity, given how simple it'd be to get with maven-changes-plugin   // _flatpack_, for comparison, has quite helpful changelog
    
    + bug tracking
    
    + active   // as in "can submit a bug and expect a fixed release soon"
    
    + positive feedback   // Recommended By 51 users at sourceforge (as of now)
    
  • 2

    对于我工作的最后一个需要处理大量CSV的企业应用程序 - 几个月前 - 我在sourceforge上使用_254990,发现它简单,强大且无问题 .

  • 0

    我过去曾经使用过OpenCSV .

    import au.com.bytecode.opencsv.CSVReader;
    
    String fileName = "data.csv";
    CSVReader reader = new CSVReader(new FileReader(fileName )); 
    
     // if the first line is the header
    String[] header = reader.readNext(); 
    // iterate over reader.readNext until it returns null
    String[] line = reader.readNext();
    

    another question的答案还有其他一些选择 .

  • 6

    我们使用JavaCSV,效果很好

  • 19

    如果你打算从excel读取csv,那么有一些有趣的角落案例 . 我不记得他们所有,但apache commons csv无法正确处理它(例如,urls) .

    请务必使用引号,逗号和斜线测试excel输出 .

  • 3

    还有CSV/Excel Utility . 它假设所有thos数据都是表格式的,并从迭代器传递数据 .

  • 8

    对于StringTokenizer,CSV格式听起来很容易,但它可能会变得更加复杂 . 在德国,分号用作分隔符,包含分隔符的单元格需要转义 . 你不会用StringTokenizer轻松处理它 .

    我会去http://sourceforge.net/projects/javacsv

  • 26

    Apache Commons CSV

    看看apache中的那个 .

  • 5

    Update: 本答案中的代码适用于Super CSV 1.52 . 可以在项目网站上找到Super CSV 2.4.0的更新代码示例:http://super-csv.github.io/super-csv/index.html


    SuperCSV项目直接支持CSV单元的解析和结构化操作 . 从http://super-csv.github.io/super-csv/examples_reading.html你会发现例如

    给了一堂课

    public class UserBean {
        String username, password, street, town;
        int zip;
    
        public String getPassword() { return password; }
        public String getStreet() { return street; }
        public String getTown() { return town; }
        public String getUsername() { return username; }
        public int getZip() { return zip; }
        public void setPassword(String password) { this.password = password; }
        public void setStreet(String street) { this.street = street; }
        public void setTown(String town) { this.town = town; }
        public void setUsername(String username) { this.username = username; }
        public void setZip(int zip) { this.zip = zip; }
    }
    

    并且您有一个带 Headers 的CSV文件 . 我们假设以下内容

    username, password,   date,        zip,  town
    Klaus,    qwexyKiks,  17/1/2007,   1111, New York
    Oufu,     bobilop,    10/10/2007,  4555, New York
    

    然后,您可以创建UserBean的实例,并使用以下代码使用文件第二行的值填充它

    class ReadingObjects {
      public static void main(String[] args) throws Exception{
        ICsvBeanReader inFile = new CsvBeanReader(new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
        try {
          final String[] header = inFile.getCSVHeader(true);
          UserBean user;
          while( (user = inFile.read(UserBean.class, header, processors)) != null) {
            System.out.println(user.getZip());
          }
        } finally {
          inFile.close();
        }
      }
    }
    

    使用以下“操作规范”

    final CellProcessor[] processors = new CellProcessor[] {
        new Unique(new StrMinMax(5, 20)),
        new StrMinMax(8, 35),
        new ParseDate("dd/MM/yyyy"),
        new Optional(new ParseInt()),
        null
    };
    
  • 32

    您可以使用csvreader api并从以下位置下载:

    http://sourceforge.net/projects/javacsv/files/JavaCsv/JavaCsv%202.1/javacsv2.1.zip/download

    要么

    http://sourceforge.net/projects/javacsv/

    使用以下代码:

    / ************ For Reading ***************/
    
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    import com.csvreader.CsvReader;
    
    public class CsvReaderExample {
    
        public static void main(String[] args) {
            try {
    
                CsvReader products = new CsvReader("products.csv");
    
                products.readHeaders();
    
                while (products.readRecord())
                {
                    String productID = products.get("ProductID");
                    String productName = products.get("ProductName");
                    String supplierID = products.get("SupplierID");
                    String categoryID = products.get("CategoryID");
                    String quantityPerUnit = products.get("QuantityPerUnit");
                    String unitPrice = products.get("UnitPrice");
                    String unitsInStock = products.get("UnitsInStock");
                    String unitsOnOrder = products.get("UnitsOnOrder");
                    String reorderLevel = products.get("ReorderLevel");
                    String discontinued = products.get("Discontinued");
    
                    // perform program logic here
                    System.out.println(productID + ":" + productName);
                }
    
                products.close();
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
    }
    

    写入/附加到CSV文件

    码:

    /************* For Writing ***************************/
    
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    
    import com.csvreader.CsvWriter;
    
    public class CsvWriterAppendExample {
    
        public static void main(String[] args) {
    
            String outputFile = "users.csv";
    
            // before we open the file check to see if it already exists
            boolean alreadyExists = new File(outputFile).exists();
    
            try {
                // use FileWriter constructor that specifies open for appending
                CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');
    
                // if the file didn't already exist then we need to write out the header line
                if (!alreadyExists)
                {
                    csvOutput.write("id");
                    csvOutput.write("name");
                    csvOutput.endRecord();
                }
                // else assume that the file already has the correct header line
    
                // write out a few records
                csvOutput.write("1");
                csvOutput.write("Bruce");
                csvOutput.endRecord();
    
                csvOutput.write("2");
                csvOutput.write("John");
                csvOutput.endRecord();
    
                csvOutput.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    }
    

相关问题