POI Comma Separated Values (CSV) - au.com.bytecode.opencsv

황제낙엽 2007.01.23 11:38 조회 수 : 626 추천:192

sitelink1 http://opencsv.sourceforge.net 
sitelink2  
sitelink3  
extra_vars4  
extra_vars5  
extra_vars6  
  포함된 예제에서 AddressExample.java 를 실행해보면 CSV를 파싱하는 것을 볼 수 있다.
  클래스는 CSVReader 와 CSVWriter 두개뿐으로써 사용법 또한 매우 간단하다.
  이 패키지에서는 Standard CSV 포맷만 지원하고, MicroSoft의 엑셀포맷은 지원하지 않는다.
Sample Code

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

 /**
 * Copyright 2005 Bytecode Pty Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

public class AddressExample {
    
        private static final String ADDRESS_FILE = "addresses.csv";
     
       
        public static void main(String[] args) throws IOException {

         /** File Read */
        CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE), 't');
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            for (int i = 0; i < nextLine.length; i++) {
                System.out.print("[" + nextLine[i] + "] ");
            }
            System.out.println("");
        }

         // Try writing it back out as CSV to the console
        CSVReader reader2 = new CSVReader(new FileReader(ADDRESS_FILE), 't');
        List allElements = reader2.readAll();
        StringWriter sw = new StringWriter();
        CSVWriter writer = new CSVWriter(sw);
        writer.writeAll(allElements);
        System.out.println("nnGenerated CSV File:nn");
        System.out.println(sw.toString());

         /** File Write */
        CSVWriter writer2 = new CSVWriter(new FileWriter("yourfile.csv"), 't');
        writer2.writeAll(allElements);
        // feed in your array (or convert your data to an array)
        String[] entries = "first#second#third#fourth".split("#");
        writer2.writeNext(entries);
        writer2.close();

     }
}


opencsv

An Open Source Java csv library under commercial-friendly license... committed to changing the world, one comma at a time...

What is opencsv?

opencsv is a very simple csv (comma-separated values) parser library for Java. It was developed because all of current csv parsers I've come across don't have commercial-friendly licenses.

Where can I get it?

Source and binaries are available from Sourceforge.

What features does opencsv support?

opencsv supports all the basic csv-type things you're likely to want to do:

  • Arbitrary numbers of values per line
  • Ignoring commas in quoted elements
  • Handling quoted entries with embedded carriage returns (ie entries that span multiple lines)
  • Configurable separator and quote characters (or use sensible defaults)
  • Read all the entries at once, or use an Iterator style model
  • Creating csv files from String[] (ie. automatic escaping of embedded quote chars)

 

How do I read and parse a CSV file?

If you want to use an Iterator style pattern, you might do something like this:

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));    String [] nextLine;    while ((nextLine = reader.readNext()) != null) {        // nextLine[] is an array of values from the line        System.out.println(nextLine[0] + nextLine[1] + "etc...");    }            

Or, if you might just want to slurp the whole lot into a List, just call readAll()...

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));    List myEntries = reader.readAll();            

which will give you a List of String[] that you can iterate over. If all else fails, check out the Javadoc.

Can I use my own separators and quote characters?

Yes. There are constructors that cater for supplying your own separator and quote characters. Say you're using a tab for your separator, you can do something like this:

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), 't');                                   

And if you single quoted your escaped characters rather than double quote them, you can use the three arg constructor:

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), 't', ''');            

You may also skip the first few lines of the file if you know that the content doesn't start till later in the file. So, for example, you can skip the first two lines by doing:

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), 't', ''', 2);            

Can I write csv files with opencsv?

Yes. There is a CSVWriter in the same package that follows the same semantics as the CSVReader. For example, to write a tab separated file:

     CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), 't');     // feed in your array (or convert your data to an array)     String[] entries = "first#second#third".split("#");     writer.writeNext(entries);	writer.close();                

If you'd prefer to use your own quote characters, you may use the three arg version of the constructor, which takes a quote character (or feel free to pass in CSVWriter.NO_QUOTE_CHARACTER).

You can also customise the line terminators used in the generated file (which is handy when you're exporting from your Linux web application to Windows clients). There is a constructor argument for this purpose.

Can I dump out SQL tables to CSV?

Yes you can. Sean Sullivan added a neat feature to CSVWriter so you can pass writeAll() a ResultSet.

            	java.sql.ResultSet myResultSet = ....            	writer.writeAll(myResultSet, includeHeaders);            

Can I use opencsv in my commercial applications?

Yes. opencsv is available under a commercial-friendly Apache 2.0 license. You are free to include it in your commericial applications without any fee or charge, and you are free to modify it to suit your circumstances. To find out more details of the license, read the Apache 2.0 license agreement.

Can I get the source? More example code?

Yes. The download from the SourceForge page includes the full source in the /src directory. It's one file, so go crazy. There is also a sample addressbook csv reader in the /examples directory. And for extra marks, there's a JUnit test suite in the /test directory.

Who maintains opencsv?

opencsv was developed in a couple of hours by Glen Smith. You can read his blog for more info and contact details.

If you've found a bug, you can report it on the project page at Sourceforge. Please post a sample file that demonstrates your issue. For bonus marks, post a patch too. :-)


SourceForge.net Logo

Links:

Author Info:

번호 제목 글쓴이 날짜 조회 수
57 셀 크기 조정 (자동 크기 조정) 황제낙엽 2011.05.03 7740
56 Cell 의 wrap 설정 (텍스트 개행) file 황제낙엽 2011.05.09 2966
55 POI HSSF, XSSF, SXSSF 성능 분석 file 황제낙엽 2013.11.05 1590
54 병합된 셀의 스타일( border) 설정하기 황제낙엽 2011.05.03 1564
53 Parsing and Processing Large XML Documents with Digester Rules (해석중) file 황제낙엽 2008.05.13 1478
52 POI 셀 스타일 설정을 위한 예제 소스 file 황제낙엽 2008.05.16 1379
51 엑셀(Excel)문서 처리 패키지 황제낙엽 2007.01.22 1334
50 POI-HSSF and POI-XSSF - Java API To Access Microsoft Excel Format Files 황제낙엽 2013.11.05 984
» Comma Separated Values (CSV) - au.com.bytecode.opencsv file 황제낙엽 2007.01.23 626
48 Parsing, indexing, and searching XML with Digester and Lucene 황제낙엽 2008.05.07 429
47 POI HSSF 기능 가이드 -- 퀵·가이드 (한글) 황제낙엽 2008.05.16 373
46 JUnit 3.8에서 JUnit 4, TestNG 활용으로 황제낙엽 2007.09.17 369
45 Junit 을 이용한 효율적인 단위 테스트 전략 황제낙엽 2007.01.30 317
44 Library & Properties 파일 file 황제낙엽 2011.12.23 313
43 XSSF Examples file 황제낙엽 2011.05.04 254
42 사용자 정의 Appender 정의하여 Log4j 확장하기 황제낙엽 2009.05.28 220
41 log4j-1.2.15.jar 와 log4j.properties 예제 file 황제낙엽 2017.08.04 187
40 접속 클라이언트의 아이피별로 로그 화일 기록하기 file 황제낙엽 2009.06.01 183
39 Comma Separated Values (CSV) - com.Ostermiller.util Java Utilities 황제낙엽 2007.01.23 177
38 Apache Log4j 2 Configuration 파일 설정 황제낙엽 2020.04.01 150