任何人都可以推荐一个简单的API,将允许我使用读CSV输入文件,做一些简单的变革,然后把它写。

一个快速的谷歌已经找到了 http://flatpack.sourceforge.net/ 这看起来很有希望。

我只是想来看看有什么其他人正在使用之前,我的夫妇自己这个API。

有帮助吗?

解决方案

Apache Commons CSV

检查了 Apache共同CSV.

这个图书馆的读和写 若干变化的CSV, ,其中包括该标准的一个 RFC4180.也读写 卡分隔 文件。

  • Excel
  • InformixUnload
  • InformixUnloadCsv
  • MySQL
  • Oracle
  • PostgreSQLCsv
  • PostgreSQLText
  • RFC4180
  • TDF

其他提示

我用 OpenCSV 在过去。

import au.com.bytecode.opencsv.CSVReader;

String fileName = "data.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));

//if第一线的头 String[]头=读者。readNext();
//迭代的读者。readNext,直到返回null String[]线=读者。readNext();

有一些其他的选择的回答 另一个问题.

更新: 代码在这个答案是超级CSV1.52.更新的代码实例超CSV2.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; }
}

和你有一个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
};

阅读CSV格式的描述让我感觉到使用第3党库将低头痛于编写它自己:

维基百科列出了10个或一些已知的图书馆:

我比较库列出使用某些种类的检查清单。 OpenCSV 变成了一个赢家我(情况因人而异),结果如下:

+ 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)

我们使用 JavaCSV, ,它工作得很好

最后一企业应用程序,我的工作,需要处理的一个显着数量的CSV--几个月前-我用的 SuperCSV 在sourceforge和找到简单、稳健和问题。

你可以使用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();
        }

    }
}

还有 CSV/Excel用.它假定所有这些数据表格和提供的数据迭代器。

CSV格式听起来很容易用于StringTokenizer但它可以成为更加复杂。在这里,在德国号是用作一个分隔和细胞中含有符需要逃脱。你不会到处理,很容易与StringTokenizer.

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

如果你打算读csv从excel,然后还有一些有趣的角情况。我不可能记住他们所有,但apache commons csv是不能够处理它正确地(例如,url).

一定要试验的excel出的报价和逗号和斜线所有的地方。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top