Java导出csv文件
时间: 2023-09-04 09:15:07 浏览: 152
以下是Java导出CSV文件的示例代码:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class CsvExporter {
public static void exportCsv(String[][] data, String fileName) {
try {
FileWriter writer = new FileWriter(new File(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");
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
String[][] data = {{"Name", "Age", "Gender"}, {"Alice", "25", "Female"}, {"Bob", "30", "Male"}};
CsvExporter.exportCsv(data, "output.csv");
}
}
```
此代码将生成一个名为`output.csv`的文件,其中包含以下内容:
```
Name,Age,Gender
Alice,25,Female
Bob,30,Male
```
阅读全文