167

CSV入力ファイルの読み取り、いくつかの単純な変換、および書き込みを使用できるようにする単純なAPIを誰かが推奨できますか?

簡単なグーグルは有望に見えるhttp://flatpack.sourceforge.net/を見つけました。

このAPIに接続する前に、他の人が何を使用しているかを確認したかっただけです。

4

10 に答える 10

86

過去にOpenCSVを使用しました。

import au.com.bytecode.opencsv.CSVReader;

文字列ファイル名 = "data.csv";
CSVReader リーダー = 新しい CSVReader(新しい FileReader(ファイル名));

// 最初の行がヘッダーの場合 String[] header = reader.readNext();
// null が返されるまで、reader.readNext を繰り返します String[] line = reader.readNext();

別の質問への回答には、いくつかの選択肢がありました。

于 2008-09-19T21:10:31.540 に答える
34

アパッチコモンズ CSV

Apache Common CSVを確認してください。

このライブラリは、標準のRFC 4180を含むCSV のいくつかのバリエーションを読み書きします。また、タブ区切りファイルを読み書きします。

  • エクセル
  • InformixUnload
  • InformixUnloadCsv
  • MySQL
  • オラクル
  • PostgreSQLCsv
  • PostgreSQLText
  • RFC4180
  • TDF
于 2008-09-19T11:58:32.350 に答える
33

更新:この回答のコードは、Super CSV 1.52 用です。Super CSV 2.4.0 の更新されたコード例は、プロジェクトの Web サイトにあります: 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 のインスタンスを作成し、ファイルの 2 行目の値を入力します。

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
};
于 2010-01-27T10:33:36.103 に答える
18

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)
于 2011-07-11T22:36:48.270 に答える
8

JavaCSVを使用していますが、かなりうまく機能します

于 2008-09-19T11:06:56.243 に答える
6

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();
        }

    }
}
于 2011-06-22T09:11:32.810 に答える
6

かなりの量の CSV を処理する必要がある最後のエンタープライズ アプリケーション (数か月前)では、sourceforge でSuperCSVを使用しましたが、シンプルで堅牢で、問題がないことがわかりました。

于 2008-09-19T11:21:08.330 に答える
3

CSV/Excel Utilityもあります。すべてのデータがテーブルのようなものであると想定し、イテレータからデータを配信します。

于 2010-10-06T07:47:30.773 に答える
2

CSV形式は、StringTokenizerにとっては十分簡単に​​聞こえますが、より複雑になる可能性があります。ここドイツでは、セミコロンが区切り文字として使用されており、区切り文字を含むセルはエスケープする必要があります。StringTokenizerではそれを簡単に処理することはできません。

私はhttp://sourceforge.net/projects/javacsvに行きます

于 2008-09-19T11:17:36.357 に答える
0

Excel から csv を読み取る場合は、興味深いコーナー ケースがいくつかあります。それらすべてを思い出せませんが、apache commons csv はそれを正しく処理できませんでした (たとえば、urls を使用)。

引用符、コンマ、スラッシュをあちこちに使用して Excel 出力をテストしてください。

于 2008-09-19T11:37:05.220 に答える