java导出csv文件工具类
时间: 2023-10-06 20:09:16 浏览: 184
以下是一个简单的 Java 工具类,可以用来导出 CSV 文件:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
public class CsvExporter {
public static void export(List<String[]> data, String fileName) {
try (FileWriter writer = new FileWriter(fileName)) {
for (String[] row : data) {
for (int i = 0; i < row.length; i++) {
writer.append(row[i]);
if (i < row.length - 1) {
writer.append(",");
}
}
writer.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
使用示例:
```java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String[]> data = new ArrayList<>();
data.add(new String[]{"Name", "Age", "City"});
data.add(new String[]{"John", "25", "New York"});
data.add(new String[]{"Mary", "30", "Los Angeles"});
CsvExporter.export(data, "output.csv");
}
}
```
以上示例将生成一个名为 `output.csv` 的文件,内容如下:
```
Name,Age,City
John,25,New York
Mary,30,Los Angeles
```
阅读全文