指定数据库表名tablename对其导出为csv文件
/**
* 指定表名按照CSV文件列分隔符与CSV文件行分隔符
* 导出为CSV文件
*/
private static final String CSV_COLUMN_SEPARATOR = ",";
private static final String CSV_ROW_SEPARATOR = System.lineSeparator();
public void ExporttoCSV(String tablename) throws Exception {
StringBuffer buf = new StringBuffer();
String select_sql = "select * from " + tablename;
SqlRowSet check_rs = jdbcTemplate.queryForRowSet(select_sql);
int colcnt = check_rs.getMetaData().getColumnCount();
//读取表头内容
for (int i = 1; i <= colcnt; i++) {
String title = check_rs.getMetaData().getColumnlabel(i).toString();
buf.append(title).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_ROW_SEPARATOR);
//读取表数据内容
check_rs.beforeFirst();
while (check_rs.next()) {
for (int i = 1; i <= colcnt; i++) {
String colv = check_rs.getString(i).toString();
buf.append(colv).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_ROW_SEPARATOR);
}
//写入CSV文件
String targetPath = "/filepath/" + tablename + ".csv";//目标文件路径
File f = new File(targetPath);//新建文件
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(targetPath)),"GBK"));
bw.write(buf.toString());
bw.flush();
bw.close();
}