java导出csv文件工具类
时间: 2023-10-09 17:07:52 浏览: 59
以下是一个简单的Java导出CSV文件的工具类示例:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
public class CSVUtils {
private static final char DEFAULT_SEPARATOR = ',';
public static void writeLine(FileWriter writer, List<String> values) throws IOException {
writeLine(writer, values, DEFAULT_SEPARATOR, ' ');
}
public static void writeLine(FileWriter writer, List<String> values, char separators) throws IOException {
writeLine(writer, values, separators, ' ');
}
public static void writeLine(FileWriter writer, List<String> values, char separators, char customQuote) throws IOException {
boolean first = true;
if (separators == ' ') {
separators = DEFAULT_SEPARATOR;
}
StringBuilder sb = new StringBuilder();
for (String value : values) {
if (!first) {
sb.append(separators);
}
if (customQuote == ' ') {
sb.append(followCVSformat(value));
} else {
sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
}
first = false;
}
sb.append("\n");
writer.append(sb.toString());
}
private static String followCVSformat(String value) {
String result = value;
if (result.contains("\"")) {
result = result.replace("\"", "\"\"");
}
return result;
}
}
```
使用示例:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("data.csv");
List<String> headers = new ArrayList<>();
headers.add("Name");
headers.add("Age");
headers.add("Gender");
CSVUtils.writeLine(writer, headers);
List<String> record1 = new ArrayList<>();
record1.add("John");
record1.add("25");
record1.add("Male");
CSVUtils.writeLine(writer, record1);
List<String> record2 = new ArrayList<>();
record2.add("Jane");
record2.add("30");
record2.add("Female");
CSVUtils.writeLine(writer, record2);
writer.flush();
writer.close();
}
}
```
这个例子将生成一个名为“data.csv”的文件,包含两个记录和一个标题行。
阅读全文