Java 使用OpenCSV 编写CSV文件
逗号分隔值(CSV)文件只是一个普通的纯文本文件,逐列存储数据,并以分隔符(例如,通常是逗号”,”)将其分割。
OpenCSV是一个Java的CSV解析器库。OpenCSV支持所有你想做的基本CSV类型的操作。Java 7目前是OpenCSV的最低支持版本。Java语言没有为有效处理CSV文件提供任何本地支持,所以我们使用OpenCSV来处理Java中的CSV文件。
如何在你的项目中添加OpenCSV ?
- 对于maven项目,你可以在pom.xml文件中加入OpenCSV的maven依赖项。
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.1</version>
</dependency>
- 对于Gradle项目,你可以包括OpenCSV的依赖。
compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
- 你可以下载OpenCSV Jar并包含在你的项目类路径中。
编写CSV文件
编写CSV文件和阅读一样简单。通过传递FileWriter对象作为参数来创建CSVWriter的实例,并使用CSVWriter类的方法开始向CSV文件写入数据。写完数据后,我们需要通过调用CSVWriter类的close()方法关闭CSVWriter连接。
- 逐行写入数据 – CSVWriter可以使用writeNext()方法逐行写入数据,该方法传递一个字符串数组,每个逗号分隔的元素作为一个单独的条目。
代码:
public static void writeDataLineByLine(String filePath)
{
// first create file object for file placed at location
// specified by filepath
File file = new File(filePath);
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
// create CSVWriter object filewriter object as parameter
CSVWriter writer = new CSVWriter(outputfile);
// adding header to csv
String[] header = { "Name", "Class", "Marks" };
writer.writeNext(header);
// add data to csv
String[] data1 = { "Aman", "10", "620" };
writer.writeNext(data1);
String[] data2 = { "Suraj", "10", "630" };
writer.writeNext(data2);
// closing writer connection
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
输出: result.csv文件包含以下数据
"Name", "Class", "Marks"
"Aman", "10", "620"
"Suraj", "10", "630"
- 一次性写入所有数据–为了一次性写入数据,调用CSVWriter类的writeAll()方法,并传递一个String[]的列表作为参数,每个String[]代表文件的一行。
代码:
public static void writeDataAtOnce(String filePath)
{
// first create file object for file placed at location
// specified by filepath
File file = new File(filePath);
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
// create CSVWriter object filewriter object as parameter
CSVWriter writer = new CSVWriter(outputfile);
// create a List which contains String array
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] { "Name", "Class", "Marks" });
data.add(new String[] { "Aman", "10", "620" });
data.add(new String[] { "Suraj", "10", "630" });
writer.writeAll(data);
// closing writer connection
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Output: result.csv file with following Data
"Name", "Class", "Marks"
"Aman", "10", "620"
"Suraj", "10", "630"
用不同的分隔符写CSV文件
默认情况下,CSV的分隔符是逗号(,)。如果你想用另一个字符作为分隔符,那么它可以作为一个参数传递给CSVWriter类。
语法 :
CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd)
描述:构造CSVWriter,提供分隔符、引号、转义符和行尾。
代码
public static void writeDataForCustomSeparatorCSV(String filePath)
{
// first create file object for file placed at location
// specified by filepath
File file = new File(filePath);
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
// create CSVWriter with '|' as separator
CSVWriter writer = new CSVWriter(outputfile, '|',
CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.DEFAULT_ESCAPE_CHARACTER,
CSVWriter.DEFAULT_LINE_END);
// create a List which contains String array
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] { "Name", "Class", "Marks" });
data.add(new String[] { "Aman", "10", "620" });
data.add(new String[] { "Suraj", "10", "630" });
writer.writeAll(data);
// closing writer connection
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
输出: 包含以下数据的result.csv文件
Name|Class|Marks
Aman|10|620
Suraj|10|630
示例:
让我们创建一个java程序,生成一个分号分隔的csv文件,并包含作为输入的数据。
Input:
Enter no of rows
9
Enter Data
Name Class Marks
Aman 10 543
Amar 10 541
Sanjeet 10 555
Luv 10 580
Ranjeet 10 512
Rabi 10 540
Dev 10 333
Sunny 10 198
代码。
// Java program to illustrate
// for Writing Data in CSV file
import java.io.*;
import java.util.*;
import com.opencsv.CSVWriter;
public class ResultGenerator {
private static final String CSV_FILE_PATH
= "./result.csv";
public static void main(String[] args)
{
addDataToCSV(CSV_FILE_PATH);
}
public static void addDataToCSV(String output)
{
// first create file object for file placed at location
// specified by filepath
File file = new File(output);
Scanner sc = new Scanner(System.in);
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
// create CSVWriter with ';' as separator
CSVWriter writer = new CSVWriter(outputfile, ';',
CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.DEFAULT_ESCAPE_CHARACTER,
CSVWriter.DEFAULT_LINE_END);
// create a List which contains Data
List<String[]> data = new ArrayList<String[]>();
System.out.println("Enter no of rows");
int noOfRow = Integer.parseInt(sc.nextLine());
System.out.println("Enter Data");
for (int i = 0; i < noOfRow; i++) {
String row = sc.nextLine();
String[] rowdata = row.split(" ");
data.add(rowdata);
}
writer.writeAll(data);
// closing writer connection
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输出: 包含以下数据的result.csv文件
Name;Class;Marks
Aman;10;543
Amar;10;541
Sanjeet;10;555
Luv;10;580
Ranjeet;10;512
Rabi;10;540
Dev;10;333
Sunny;10;198