Domanda

Qualcuno può consigliare un API semplice che mi permetta di usare leggi CSV file di input, fare alcune semplici trasformazioni, e poi scrivere.

Una rapida occhiata su google ha trovato http://flatpack.sourceforge.net/ che sembra promettente.

Volevo solo controllare ciò che gli altri stanno usando la prima coppia a me stesso di questa API.

È stato utile?

Soluzione

Apache Commons CSV

Check out Apache Comune CSV.

Questa libreria di legge e scrive diverse varianti di CSV, tra cui quella standard RFC 4180.Legge/scrive Delimitato da tabulazioni i file.

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

Altri suggerimenti

Ho usato OpenCSV in passato.

import au.com.bytecode.opencsv.CSVReader;

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

// se la prima riga è l'intestazione String[] header = lettore.readNext();
// iterare lettore.readNext fino a quando non restituisce null String[] linea = lettore.readNext();

Ci sono state alcune altre scelte le risposte un'altra domanda.

Aggiornamento: Il codice in questa risposta è per il Super CSV 1.52.Aggiornato esempi di codice per Super CSV 2.4.0 può essere trovato presso il sito web del progetto:http://super-csv.github.io/super-csv/index.html


Il SuperCSV progetto direttamente supporta l'analisi e strutturato manipolazione del CSV cellule.Da http://super-csv.github.io/super-csv/examples_reading.html troverete ad esempio

data una classe

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

e che si dispone di un file CSV con un colpo di testa.Si ipotizzi il seguente contenuto

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

È quindi possibile creare un'istanza della UserBean e popolarlo con i valori della seconda riga del file con il codice riportato di seguito

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

utilizzando il seguente "la manipolazione specifica"

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

La lettura in formato CSV descrizione mi fa sentire che l'uso di 3rd party biblioteca sarebbe meno mal di testa che scrivere io:

Wikipedia elenca 10 o qualcosa di noto librerie:

Io rispetto le librerie elencate utilizzando un qualche tipo di lista di controllo. OpenCSV si è rivelato un vincitore per me (YMMV) con i seguenti risultati:

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

Usiamo JavaCSV, funziona abbastanza bene

Per l'ultima di applicazioni enterprise che ho lavorato su quel necessarie per gestire una notevole quantità di CSV -- un paio di mesi fa, ho utilizzato SuperCSV su sourceforge e l'ho trovato semplice, robusto e problema-gratis.

È possibile utilizzare csvreader api & download dal seguente percorso:

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

o

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

Utilizzare il codice riportato di seguito:

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

    }

}

Scrivere / Aggiunta di file CSV

Codice:

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

    }
}

C'è anche CSV/Excel Utility.Si presuppone che tutti quei dati di tabella come e fornisce i dati da Iteratori.

Il formato CSV suona abbastanza facile per StringTokenizer, ma può diventare molto complicato.Qui in Germania un punto e virgola come delimitatore e le celle contenenti i delimitatori bisogno di essere sfuggito.Tu non stai andando a gestire facilmente con StringTokenizer.

Vorrei andare per http://sourceforge.net/projects/javacsv

Se avete intenzione di leggere csv excel, poi ci sono alcuni interessanti casi di angolo.Io non li ricordo tutti, ma l'apache commons csv non era in grado di gestire correttamente (con, per esempio, url).

Assicurati di testare output di excel con le citazioni e le virgole e le barre in tutto il luogo.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top