背景:SAAS平台的导出支持csv格式,单机版暂不支持,现有一个国外的项目,需求是导出csv格式的文件,记录一下
package core.export;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import core.database.entity.Entity;
public class CSVFile {
protected static Logger log4j= LogManager.getLogger("CSVFile");
private File file;
private BufferedWriter writer = null;
private String[] headerArray = null;
public CSVFile(String pathname) {
createFile(pathname);
}
public CSVFile(String pathname, String headers) {
createFile(pathname);
if (headers != null)
setHeaders(headers);
}
private void createFile(String pathname) {
if (!pathname.endsWith(".csv"))
pathname += ".csv";
file = new File(pathname);
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
try {
file.createNewFile();
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
file), "GB2312"), 1024);
} catch (IOException e) {
log4j.warn("创建文件时发生错误: {}", pathname, e);
}
}
private String getCSVParsedString(String content) {
if (content == null)
return "";
//csv格式如果有逗号,整体用双引号括起来;如果里面还有双引号就替换成两个双引号,这样导出来的格式就不会有问题了
String tempDescription=content;
//如果有逗号
if(content.contains(",")){
//如果还有双引号,先将双引号转义,避免两边加了双引号后转义错误
if(content.contains("\"")){
tempDescription=content.replace("\"", "\"\"");
}
//在将逗号转义
tempDescription="\""+tempDescription+"\"";
}
return tempDescription;
}
public void setHeaders(String headers) {
if (this.headerArray != null) {
log4j.warn("CSVFile already have headers, can't accept another headers: {}", headers);
return;
}
String tmp[] = headers.split(",");
headerArray = new String[tmp.length];
try {
boolean isFirst = true;
for (int i = 0; i < tmp.length; i++) {
String header[] = tmp[i].split("\\|");
if (isFirst)
isFirst = false;
else
writer.write(',');
writer.write(getCSVParsedString(header[0]));
if (header.length>1)
headerArray[i] = header[1];
else
headerArray[i] = header[0];
}
writer.newLine();
} catch (IOException e) {
log4j.warn("写入头部时发生错误: {}", headers, e);
}
}
public void writeRow(Entity entity) {
boolean isFirst = true;
try {
for (String string : headerArray) {
if (isFirst)
isFirst = false;
else
writer.write(',');
writer.write(getCSVParsedString(entity.getStringValue(string)));
}
writer.newLine();
} catch (IOException e) {
log4j.warn("写入数据时发生错误", e);
}
}
public void writeRow(List<String> list) {
boolean isFirst = true;
try {
for (String str : list) {
if (isFirst)
isFirst = false;
else
writer.write(',');
writer.write(getCSVParsedString(str));
}
writer.newLine();
} catch (IOException e) {
log4j.warn("写入数据时发生错误", e);
}
}
public File finishWrite() {
try {
writer.flush();
writer.close();
} catch (IOException e) {
log4j.warn("结束写入时发生错误", e);
}
return file;
}
public static void main(String[] args) {
CSVFile f = new CSVFile("/opt/demo5.csv", "name,sex");
System.out.println(f);
Entity e = new Entity("CustomerInfo");
e.setValue("name", "v1");
e.setValue("sex", "v2");
System.out.println(e);
f.writeRow(e);
f.finishWrite();
System.out.println("ok");
}
}