문제

CSV 입력 파일을 읽고 몇 가지 간단한 변환을 수행한 다음 작성할 수 있는 간단한 API를 추천해 줄 수 있는 사람이 있나요?

구글이 빠르게 찾아낸 http://Flatpack.sourceforge.net/ 유망 해 보입니다.

나는 이 API에 연결하기 전에 다른 사람들이 무엇을 사용하고 있는지 확인하고 싶었습니다.

도움이 되었습니까?

해결책

아파치 커먼즈 CSV

확인해 보세요 아파치 공통 CSV.

이 라이브러리는 읽고 씁니다. CSV의 여러 변형, 표준을 포함하여 RFC 4180.또한 읽기/쓰기 탭으로 구분 파일.

  • 뛰어나다
  • Informix언로드
  • InformixUnloadCsv
  • MySQL
  • 신탁
  • PostgreSQLCsv
  • PostgreSQL텍스트
  • RFC4180
  • TDF

다른 팁

나는 사용했다 오픈CSV 과거에.

import au.com.bytecode.opencsv.CSVReader;

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

// 첫 번째 줄이 헤더 문자열 인 경우 [] header = reader.readnext ();
// reader.readnext를 반복 할 때까지 null string [] line = reader.readnext ();

에 대한 답변에는 다른 선택 사항이 있었습니다. 다른 질문.

업데이트: 이 답변의 코드는 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; }
}

헤더가 포함된 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 형식 설명을 읽으면 타사 라이브러리를 사용하는 것이 직접 작성하는 것보다 덜 골치 아픈 것 같은 느낌이 듭니다.

Wikipedia에는 ​​10개 이상의 알려진 라이브러리가 나열되어 있습니다.

일종의 체크리스트를 사용하여 나열된 라이브러리를 비교했습니다. 오픈CSV 다음 결과로 나(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)

우리는 사용 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 유틸리티.모든 데이터가 테이블과 유사하고 Iterator에서 데이터를 전달한다고 가정합니다.

CSV 형식은 StringTokenizer에 충분히 쉬운 것처럼 보이지만 더 복잡해질 수 있습니다.독일에서는 세미콜론이 구분 기호로 사용되며 구분 기호가 포함된 셀은 이스케이프해야 합니다.StringTokenizer를 사용하면 이를 쉽게 처리할 수 없습니다.

나는 갈 것이다 http://sourceforge.net/projects/javacsv

Excel에서 CSV를 읽으려는 경우 몇 가지 흥미로운 특수 사례가 있습니다.모두 기억할 수는 없지만 Apache Commons CSV는 이를 올바르게 처리할 수 없었습니다(예: URL 사용).

여기저기서 따옴표, 쉼표, 슬래시를 사용하여 Excel 출력을 테스트하십시오.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top