把数据库数据 导入CSV 工具类

Table

public class Table {

	private List<Map<String, String>> columns = new ArrayList<Map<String, String>>();
	private String tableName;

	public List<Map<String, String>> getColumns() {
		return columns;
	}

	public void setColumns(List<Map<String, String>> columns) {
		this.columns = columns;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

}

ExportQueryDataLToCSV


public interface ExportQueryDataLToCSV {

	abstract void exportCSV(String sql, Object[] params, String stateMentId,
			String defauleFileName) throws SQLException;

	abstract public void clearData(String defauleFileName);

}


ExportQueryDataLToCSVImpl


@Component("exportCSVImpl")
public class ExportQueryDataLToCSVImpl implements ExportQueryDataLToCSV {

	@Autowired
	private transient JdbcTemplate jdbcTemplate;

	private String baseDir = "./TestSource/";

	private Table table;

	public void initTable(String sql, StringBuffer buf, String stateMentId) {
		String[] words = sql.split("[ ]+");
		int i = 0;
		for (; i < words.length; i++) {
			if ("FROM".equals(words[i].toUpperCase()))
				break;
		}
		buf.append("STATEMENT ID" + "," + stateMentId + "\r\n");
		buf.append("TABLE NAME" + "," + words[i + 1] + "\r\n");

		table = new Table();
		table.setTableName(words[i + 1].toUpperCase());

	}

	public void exportCSV(String sql, Object[] params, String stateMentId,
			String defauleFileName) throws SQLException {

		StringBuffer buf = new StringBuffer();
		PrintWriter printer = null;
		printer = getDefaultPrinter(defauleFileName);
		initTable(sql, buf, stateMentId);// Table

		List<Map<String, Object>> result = jdbcTemplate.queryForList(sql,
				params);

		if (result != null && result.size() > 0) {
			for (Map<String, Object> map : result) {
				for (String key : map.keySet()) {
					Map<String, String> tempMap = new HashMap<String, String>();
					tempMap.put(key, getObjectType(map.get(key)));
					buf.append(key + ",");
					table.getColumns().add(tempMap);
				}
				buf.append("\r\n");
				break;

			}
		}

		if (result != null && result.size() > 0) {
			for (Map<String, Object> map : result) {
				for (Map<String, String> columnMap : table.getColumns()) {
					buf.append(gernateString(map, columnMap));
				}
				buf.append("\r\n");
			}
			buf.append("\r\n");

			try {
				printer.append(buf);
				printer.flush();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (printer != null)
					printer.close();
			}
		} else {
			LOGGER.debug("Without data from execute query sql !");
		}

	}

	public String gernateString(Map<String, Object> mapData,
			Map<String, String> columnMap) {
		StringBuffer tempBuf = new StringBuffer();
		String key = (String) columnMap.keySet().toArray()[0];
		String data = "";

		if (mapData.get(key) != null)
			if (columnMap.get(key).equals("Boolean")) {
				Object obj = mapData.get(key);
				boolean bl = (Boolean) obj;
				data = bl ? "Y" : "N";
			} else
				data = mapData.get(key).toString();
		String appendChar = "'";
		if (columnMap.get(key).equals("Integer"))
			appendChar = "";

		if (mapData.get(key) != null)
			tempBuf.append(appendChar + data + appendChar + ",");
		else
			tempBuf.append(data + ",");
		return tempBuf.toString();
	}

	// get default printer
	public PrintWriter getDefaultPrinter(String defauleFileName) {
		PrintWriter printer = null;
		printer = getWrite(buildCSVPath(defauleFileName));
		return printer;

	}

	public PrintWriter getWrite(File file) {
		PrintWriter printer = null;
		try {

			printer = new PrintWriter(new FileOutputStream(file, true));

		} catch (FileNotFoundException e) {
			LOGGER.debug("PrintWrite create failed!!");
		}
		return printer;

	}

	public File buildCSVPath(String defauleFileName) {
		File tmpFile = getClassPathFile(defauleFileName);
		if (tmpFile.isFile()) {
			return tmpFile;
		}
		File baseFile = new File(baseDir);
		if (!baseFile.exists()) {
			baseFile.mkdirs();
		}
		File defaultFile = new File(baseDir + defauleFileName);
		if (!defaultFile.exists()) {
			try {
				defaultFile.createNewFile();
			} catch (IOException e) {

			}
		}

		return defaultFile;
	}

	private File getClassPathFile(String classPath) {
		ClassLoader loader = this.getClass().getClassLoader();
		if (null == loader) {
			loader = ClassLoader.getSystemClassLoader();
		}
		String path = classPath.startsWith("/") ? classPath.substring(1)
				: classPath;
		URL url = loader.getResource(path);
		return new File(null == url ? loader.getResource("").getPath() + path
				: url.getPath());
	}

	public String getObjectType(Object obj) {
		String type = "String";
		if (obj instanceof String) {
			type = "String";
		} else if (obj instanceof Integer) {
			type = "Integer";
		} else if (obj instanceof BigDecimal) {
			type = "BigDecimal";
		} else if (obj instanceof Boolean) {
			type = "Boolean";
		}

		return type;

	}

	public void clearData(String defauleFileName) {
		File defaultFile = new File(baseDir + defauleFileName);
		if (defaultFile.exists()) {
			StringBuffer buf = new StringBuffer();
			PrintWriter printer = null;
			try {
				printer = new PrintWriter(new FileOutputStream(defaultFile,
						false));
				printer.append(buf);
				printer.flush();
				LOGGER.debug("Query data cleared");

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (printer != null)
					printer.close();
			}
		}
	}
}

测试类


public class TestHello {

	@Autowired
	@Qualifier("exportCSVImpl")
	private ExportQueryDataLToCSV exportToCSVImpl;

	private String defauleFileName = "hello.csv";

	@Test
	public void exportMstrTbl4Rec3() {
		try {
			exportCSV();

		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	private void exportCSV() throws SQLException {
		try {
			StringBuilder sb = new StringBuilder();
			sb.append("select * from table");
			String sql = sb.toString();

			exportToCSVImpl.exportCSV(sql, null, "hello", defauleFileName);

		} catch (Exception e) {

			e.printStackTrace();
		}

	}
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值