首页 > 解决方案 > psql import .csv - 双引号字段和单双引号值

问题描述

你好堆栈溢出者,

奇怪的问题。我在使用 psql 命令行参数导入 .csv 文件时遇到问题...

.csv 以逗号分隔,并且在其中包含逗号的单元格/字段周围有双引号。我遇到了一个问题,其中一个单元格/字段有一个用于英寸的双引号。所以在下面的例子中,它认为底部的两行都是一个单元格/字段。

我似乎找不到正确进行此导入的方法。我希望不必对文件本身进行更改,只需调整我的 psql 命令。

Ex:
number, number, description  (Headers)
123,124,"description, description"
123,124,description, TV 55"
123,124,description, TV 50"

Command Ex:
\copy table FROM 'C:\Users\Desktop\folder\file.csv' CSV HEADER
\copy table FROM 'C:\Users\Desktop\folder\file.csv' WITH CSV HEADER QUOTE '"' ESCAPE '\' 

我注意到使用 excel 保存解决了这个问题... Excel 将记录格式化为...

number, number, description  (Headers)
123,124,"description, description"
123,124,"description, TV 55"""
123,124,"description, TV 50"""

不过,我不想使用 excel 保存,因为我的数字已转换为科学记数法,并且在 excel 中打开文件时会立即删除前导零。

标签: postgresqlcsvpsql

解决方案


这是一个丑陋的黑客,但你可以导入到一个单列表中\copy table from '/path/to/file' CSV quote e'\x01' delimiter e'\x02',然后尝试使用正则表达式函数在 SQL 中修复它。这仅适用于相当小的 CSV,因为您在导入时复制了单列表中的数据。

testdb=# create table import_data(t text);
CREATE TABLE
testdb=# \! cat /tmp/oof.csv
num0,num1,descrip
123,124,"description, description"
123,124,description, TV 55"
123,124,"description, TV 50""
testdb=# \copy import_data from /tmp/oof.csv csv header quote e'\x01' delimiter e'\x02'
COPY 3
testdb=# CREATE TABLE fixed AS
SELECT
  (regexp_split_to_array(t, ','))[1] num1,
  (regexp_split_to_array(t, ','))[2] num2,
  regexp_replace(
        regexp_replace(regexp_replace(t, '([^,]+,[^,]+),(.*)', '\2'),
                       '"(.*?)"', '\1'),
        '(.*)(")?', '\1\2') as descrip
FROM import_data;
SELECT 3
testdb=# select * from fixed;
 num1 | num2 |         descrip          
------+------+--------------------------
 123  | 124  | description, description
 123  | 124  | description, TV 55"
 123  | 124  | description, TV 50"
(3 rows)

推荐阅读