如何在 Java 中将数据写入 .csv 文件?
名为 OpenCSV 的库提供 API 用于从 .CSV 文件读取和写入数据。这里解释了如何使用 Java 程序编写 .csv 文件的内容。
Maven 依赖
<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>
com.opencsv 包的 CSVWriter 类表示一个简单的 csv 写入器。在实例化此类时,您需要将表示要写入数据的文件的 Writer 对象作为参数传递给其构造函数。
它提供了名为 **writeAll()** 和 **writeNext()** 的方法来将数据写入 .csv 文件。
使用 writeNext() 方法
CSVWriter 类的 writeNext() 方法将下一行写入 .csv 文件
示例
以下 Java 程序演示了如何使用 writeNext() 方法将数据写入 .csv 文件。
import java.io.FileWriter; import com.opencsv.CSVWriter; public class WritingToCSV { public static void main(String args[]) throws Exception { //Instantiating the CSVWriter class CSVWriter writer = new CSVWriter(new FileWriter("D://output.csv")); //Writing data to a csv file String line1[] = {"id", "name", "salary", "start_date", "dept"}; String line2[] = {"1", "Krishna", "2548", "2012-01-01", "IT"}; String line3[] = {"2", "Vishnu", "4522", "2013-02-26", "Operations"}; String line4[] = {"3", "Raja", "3021", "2016-10-10", "HR"}; String line5[] = {"4", "Raghav", "6988", "2012-01-01", "IT"}; //Writing data to the csv file writer.writeNext(line1); writer.writeNext(line2); writer.writeNext(line3); writer.writeNext(line4); //Flushing data from writer to file writer.flush(); System.out.println("Data entered"); } }
输出
Data entered
使用 writeAll() 方法
此方法接受一个包含要写入内容的 List 对象(字符串数组类型),并将其一次性写入 .csv 文件。
示例
以下 Java 程序演示了如何使用 writeAll() 方法将内容写入 .csv 文件。
import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import com.opencsv.CSVWriter; public class WritingToCSV { public static void main(String args[]) throws Exception { //Instantiating the CSVWriter class CSVWriter writer = new CSVWriter(new FileWriter("D://output.csv")); //Writing data to a csv file String line1[] = {"id", "name", "salary", "start_date", "dept"}; String line2[] = {"1", "Krishna", "2548", "2012-01-01", "IT"}; String line3[] = {"2", "Vishnu", "4522", "2013-02-26", "Operations"}; String line4[] = {"3", "Raja", "3021", "2016-10-10", "HR"}; String line5[] = {"4", "Raghav", "6988", "2012-01-01", "IT"}; //Instantiating the List Object List list = new ArrayList(); list.add(line1); list.add(line2); list.add(line3); list.add(line4); list.add(line5); //Writing data to the csv file writer.writeAll(list); writer.flush(); System.out.println("Data entered"); } }
输出
Data entered
广告