import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
/**
* CSV文件示例程序
* @version 1.0 2014/10/30
*/
public class CsvFileCreator {
public static void main(String[] args) {
CsvFileCreator example = new CsvFileCreator();
example.createCsv();
}
/**
* 创建CSV文件
*/
public void createCsv(){
//换行符
final String NEW_LINE = "\n";
//文件名称
String fileName = "D:\\MyCsv.csv";
try {
//标题头
String title = "序号,姓名,年龄,身高";
StringBuilder csvStr = new StringBuilder();
csvStr.append(title).append(NEW_LINE);
//数据行
for(String csvData : getCsvRows()){
csvStr.append(csvData).append(NEW_LINE);
}
//写文件
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), "GB2312"));
writer.write(csvStr.toString());
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取CSV行数据,各个值之间使用英文逗号分隔
* @return List<String>
*/
private List<String> getCsvRows(){
List<String> result = new ArrayList<String>();
result.add("1,Mr Zhang,20,170");
result.add("2,Mrs Wang,18,175");
result.add("3,Li,30,178");
result.add("4,Zhao,19,175");
result.add("5,Ms Feng,18,165");
return result;
}
}
温馨提示:内容为网友见解,仅供参考