数据库数据导出到csv文件

以下是程序中用到的方法

// 写入数据

public static StringBuffer writeCsv(

List<LinkedHashMap<String, Object>> mapList, String csvstr)

throws Exception {

StringBuffer logsb = new StringBuffer();

FileOutputStream out = null;

OutputStreamWriter osw = null;

BufferedWriter bw = null;

try {

 

File csvfile = new File(csvstr); // logFile 是路径,就叫做String logFile

 

// 生成路径+想要的文件名+".csv";

//System.out.println(csvstr);

 

out = new FileOutputStream(csvfile);

osw = new OutputStreamWriter(out, "GB2312");

bw = new BufferedWriter(osw);

 

// CSV默认是已逗号","分隔单元格的。这里是表头

 

if (mapList.size() > 0) {

// 表头

// System.out.println("开始写表头");

String content = "";

for (Entry<String, Object> entry : mapList.get(0).entrySet()) {

content += entry.getKey() + ",";

}

bw.write(content + "\r\n");

// System.out.println("表头写入完成");

// System.out.println("开始写入内容");

// 数据

for (int i = 0; i < mapList.size(); i++) {

String datastr = "";

HashMap<String, Object> propertymap = mapList.get(i);

for (Entry<String, Object> entry : propertymap.entrySet()) {

String obj = entry.getValue() + "";

if (obj.contains("oracle.sql.CLOB")) {

obj = oracleclobToString(entry.getValue());

}

if (obj.contains("\"")) {

obj = obj.replace("\"", "\"\"");

}

if (obj.contains(",")) {

obj = "\"" + obj + "\"";

}

datastr += obj + ",";

}

bw.write(datastr + "\r\n");

bw.flush();

}

// System.out.println("内容写入完成");

 

}

 

logsb.append("INFO  导入CSV共" + mapList.size() + "行\r\n");

 

} catch (Exception e) {

throw e;

} finally {

bw.close();

osw.close();

out.close();

}

return logsb;

}

 

 

// CLOB数据转换成String

// oracle.sql.Clob类型转换成String类型

public static String oracleclobToString(Object objclob) throws Exception {

String reString = "";

Clob clob = (Clob) objclob;

Reader is = clob.getCharacterStream();// 得到流

BufferedReader br = new BufferedReader(is);

String s = br.readLine();

StringBuffer sb = new StringBuffer();

while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING

sb.append(s);

s = br.readLine();

}

reString = sb.toString();

return reString;

}

此处注意的是

1、数据库中字段的类型如果是Clob类型的话,则需要转换成String类型,否则写入到csv中是无法看到数据

2、写入CSV文件中的字段值里面的有双引号的则需要转换,否则写入数据格式就错开,转换方式则是用两个双引号替换,替换后则写出后还是一个双引号

3、写入的时候,最好一行一行写入,否则数据多的时候会包溢出

// CLOB数据转换成String // oracle.sql.Clob类型转换成String类型

 

 

此方法可以用到备份数据,导出csv文件用到,

 

 

 

 

猜你喜欢

转载自zhao103804.iteye.com/blog/2236556