【发布时间】:2019-04-09 11:32:55
【问题描述】:
我正在使用 Java SAX 解析器从 Excel 中读取数据(使用 XSSF XLSX2CSV 类)并将其加载到 Greenplum 数据库中。我正在使用以下链接中的代码:
我从上述代码中捕获 PrintStream 输出,将其转换为 ByteInputStream,然后使用本机批量加载实用程序 - 复制 - 命令将其加载到 Postgres(Greenplum)。
我在 XLSX2CSV 的主要方法中修改了以下内容以捕获打印流并将其转换为字节输入流。
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos, true, "UTF-8");
// The package open is instantaneous, as it should be.
try (OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ)) {
XLSX2CSV xlsx2csv = new XLSX2CSV(p, ps, minColumns);
xlsx2csv.process();
System.out.println(ps);
String data = new String(baos.toByteArray(), StandardCharsets.UTF_8);
System.out.println(data);
byte[] bytes = data.getBytes("UTF8");
ByteArrayInputStream orinput = new ByteArrayInputStream(bytes);
String dbURL1 = "jdbc:postgresql://xxxxx:xxxxx/xxxxx";
String user = "xxxxxx";
String pass = "xxxxxx";
Connection GPConnection = DriverManager.getConnection(dbURL1, user, pass);
Statement GPsqlStatement = GPConnection.createStatement();
String GPStgTableTrunc = "truncate test_table";
GPsqlStatement.execute(GPStgTableTrunc);
System.out.print("Load to Greenplum starts "+
Calendar.getInstance().getTime() + "\r\n");
CopyManager copyManager = new CopyManager((BaseConnection) GPConnection);
copyManager.copyIn("copy test_table from stdin csv",orinput);
System.out.print("Load to Greenplum ends "+
Calendar.getInstance().getTime() + "\r\n");
但是在转换为 ByteInputStream 的过程中,换行符似乎丢失了,并且在加载到 Greenplum 时出现以下错误..
ERROR: COPY metadata not found. This probably means that there is a mixture of newline types in the data. Use the NEWLINE keyword in order to resolve this reliably. (seg40 sdw6.gphd.local:1025 pid=101588)
当我打印字符串“数据”时,它似乎有换行符,并且值被正确打印。但是在批量加载到数据库时它不会加载。
如何在上述情况下保留换行符以便正确加载?或者,如果有办法将 printsream 转换为标准输入,那也可以。谢谢!
【问题讨论】:
-
如何添加新行?
\n或\r -
XLSX2CSV 用这一行将它添加到最后一行函数中.. output.append('\n');
-
添加 \r 也应该有帮助
标签: java apache-poi sax greenplum xssf