用于 Java 的 CSV API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/101100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSV API for Java
提问by David Turner
Can anyone recommend a simple API that will allow me to use read a CSV input file, do some simple transformations, and then write it.
任何人都可以推荐一个简单的 API,它允许我使用读取 CSV 输入文件,进行一些简单的转换,然后编写它。
A quick google has found http://flatpack.sourceforge.net/which looks promising.
一个快速的谷歌发现http://flatpack.sourceforge.net/看起来很有希望。
I just wanted to check what others are using before I couple myself to this API.
在我将自己连接到这个 API 之前,我只是想检查一下其他人正在使用什么。
采纳答案by daveb
Apache Commons CSV
Apache Commons CSV
Check out Apache Common CSV.
This library reads and writes several variations of CSV, including the standard one RFC 4180. Also reads/writes Tab-delimitedfiles.
该库读取和写入CSV 的多种变体,包括标准的RFC 4180。还读取/写入制表符分隔的文件。
- Excel
- InformixUnload
- InformixUnloadCsv
- MySQL
- Oracle
- PostgreSQLCsv
- PostgreSQLText
- RFC4180
- TDF
- 电子表格
- Informix卸载
- InformixUnloadCsv
- MySQL
- 甲骨文
- PostgreSQL CSV
- PostgreSQL 文本
- RFC4180
- TDF
回答by paul
The CSV format sounds easy enough for StringTokenizer but it can become more complicated. Here in Germany a semicolon is used as a delimiter and cells containing delimiters need to be escaped. You're not going to handle that easily with StringTokenizer.
CSV 格式对于 StringTokenizer 来说听起来很简单,但它可能会变得更复杂。在德国,分号用作分隔符,包含分隔符的单元格需要转义。使用 StringTokenizer 不会那么容易处理。
I would go for http://sourceforge.net/projects/javacsv
回答by Cheekysoft
回答by daveb
If you intend to read csv from excel, then there are some interesting corner cases. I can't remember them all, but the apache commons csv was not capable of handling it correctly (with, for example, urls).
如果您打算从 excel 读取 csv,那么有一些有趣的角落案例。我不记得所有这些,但是 apache commons csv 无法正确处理它(例如,使用 url)。
Be sure to test excel output with quotes and commas and slashes all over the place.
请务必使用引号、逗号和斜线到处测试 excel 输出。
回答by Jay R.
I've used OpenCSVin the past.
我过去使用过OpenCSV。
import au.com.bytecode.opencsv.CSVReader;
String fileName = "data.csv"; CSVReader reader = new CSVReader(new FileReader(fileName ));// if the first line is the header String[] header = reader.readNext();
// iterate over reader.readNext until it returns null String[] line = reader.readNext();
There were some other choices in the answers to another question.
在另一个问题的答案中还有其他一些选择。
回答by kbg
Update:The code in this answer is for Super CSV 1.52. Updated code examples for Super CSV 2.4.0 can be found at the project website: http://super-csv.github.io/super-csv/index.html
更新:此答案中的代码适用于 Super CSV 1.52。Super CSV 2.4.0 的更新代码示例可以在项目网站上找到:http: //super-csv.github.io/super-csv/index.html
The SuperCSV project directly supports the parsing and structured manipulation of CSV cells. From http://super-csv.github.io/super-csv/examples_reading.htmlyou'll find e.g.
SuperCSV 项目直接支持对 CSV 单元格的解析和结构化操作。从http://super-csv.github.io/super-csv/examples_reading.html你会发现例如
given a class
给定一个班级
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; }
}
and that you have a CSV file with a header. Let's assume the following content
并且您有一个带有标题的 CSV 文件。让我们假设以下内容
username, password, date, zip, town
Klaus, qwexyKiks, 17/1/2007, 1111, New York
Oufu, bobilop, 10/10/2007, 4555, New York
You can then create an instance of the UserBean and populate it with values from the second line of the file with the following code
然后,您可以创建 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();
}
}
}
using the following "manipulation specification"
使用以下“操作规范”
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
};
回答by Frank
There is also CSV/Excel Utility. It assumes all thos data is table-like and delivers data from Iterators.
还有CSV/Excel 实用程序。它假设所有这些数据都是类似表格的,并从迭代器传递数据。
回答by Dhananjay Joshi
You can use csvreader api & download from following location:
您可以使用 csvreader api 并从以下位置下载:
http://sourceforge.net/projects/javacsv/files/JavaCsv/JavaCsv%202.1/javacsv2.1.zip/download
http://sourceforge.net/projects/javacsv/files/JavaCsv/JavaCsv%202.1/javacsv2.1.zip/download
or
或者
http://sourceforge.net/projects/javacsv/
http://sourceforge.net/projects/javacsv/
Use the following code:
使用以下代码:
/ ************ 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();
}
}
}
Write / Append to CSV file
写入/附加到 CSV 文件
Code:
代码:
/************* 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();
}
}
}
回答by gnat
Reading CSV format description makes me feel that using 3rd party library would be less headache than writing it myself:
阅读CSV格式的描述让我觉得使用3rd party library会比自己编写更不头痛:
Wikipedia lists 10 or something known libraries:
维基百科列出了 10 个或一些已知的库:
I compared libs listed using some kind of check list. OpenCSVturned out a winner to me (YMMV) with the following results:
我比较了使用某种检查列表列出的库。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)