當前位置:首頁 >  站長 >  數(shù)據(jù)庫 >  正文

如何將postgresql數(shù)據(jù)庫表內(nèi)數(shù)據(jù)導(dǎo)出為excel格式

 2021-04-22 16:54  來源: 腳本之家   我來投稿 撤稿糾錯

  域名預(yù)訂/競價,好“米”不錯過

本文主要用于介紹如何使用copy或者\copy命令將postgresql數(shù)據(jù)庫內(nèi)表的數(shù)據(jù)導(dǎo)出為excel格式,方便用戶查看編輯。

copy命令同\copy命令語法上相同,區(qū)別在于copy必須使用能夠超級用戶使用,copy … to file 中的文件都是數(shù)據(jù)庫服務(wù)器所在的服務(wù)器上的文件,而\copy 一般用戶即可執(zhí)行且\copy 保存或者讀取的文件是在客戶端所在的服務(wù)器。本文主要以copy命令作為介紹重點,使用copy命令將表內(nèi)數(shù)據(jù)倒為csv格式文件即為excel格式。

1、copy命令語法

COPY { 表名 [ ( 列名稱 [, ...] ) ] | ( 查詢 ) }
TO { '文件名' | PROGRAM '命令' | STDOUT }
 [ [ WITH ] ( 選項 [, ...] ) ]

選項可以是下列內(nèi)容之一
 FORMAT 格式_名稱
 FREEZE [ 布爾 ]
 DELIMITER '分隔字符'
 NULL '空字符串'
 HEADER [ 布爾 ]
 QUOTE '引用字符'
 ESCAPE '轉(zhuǎn)義字符'
 FORCE_QUOTE { ( 列名稱 [, ...] ) | * }
 FORCE_NOT_NULL ( 列名稱 [, ...] )
 FORCE_NULL ( 列名稱 [, ...] )
 ENCODING 'encoding_name(編碼名)'

 

2、多場景使用介紹

①查看現(xiàn)有表數(shù)據(jù)

test=# select * from test;
user_id | user_name | age | gender |     remark    
---------+---------------+-----+--------+----------------------------------------------
  1 | Jackie Chan | 45 | male | "police story","project A","rush hour"
  3 | Brigitte Li | 46 | female |
  4 | Maggie Cheung | 39 | female |
  5 | Jet Li  | 41 | male | "Fist of Legend","Once Upon a Time in China"
  2 | Gong Li  | 38 | female | "Farewell My Concubine","Lifetimes Living"
(5 行記錄)

 

②帶列名導(dǎo)出,默認情況下使用,作為分隔符

test=# copy test to '/tmp/test1.csv' with csv header;
COPY 5
test=# \! cat /tmp/test1.csv
user_id,user_name,age,gender,remark
1,Jackie Chan,45,male,"""police story"",""project A"",""rush hour"""
3,Brigitte Li,46,female,
4,Maggie Cheung,39,female,
5,Jet Li,41,male,"""Fist of Legend"",""Once Upon a Time in China"""
2,Gong Li,38,female,"""Farewell My Concubine"",""Lifetimes Living"

 

③帶列名導(dǎo)出,指定使用|作為分隔符

test=# copy test to '/tmp/test1.csv' with csv header DELIMITER '|';
COPY 5
test=# \! cat /tmp/test1.csv
user_id|user_name|age|gender|remark
1|Jackie Chan|45|male|"""police story"",""project A"",""rush hour"""
3|Brigitte Li|46|female|
4|Maggie Cheung|39|female|
5|Jet Li|41|male|"""Fist of Legend"",""Once Upon a Time in China"""
2|Gong Li|38|female|"""Farewell My Concubine"",""Lifetimes Living"

 

④帶列名導(dǎo)出,將空字符替換為指定值導(dǎo)出

test=# copy test to '/tmp/test1.csv' with csv header null 'to be supplemented';
COPY 5
test=# \! cat /tmp/test1.csv
user_id,user_name,age,gender,remark
1,Jackie Chan,45,male,"""police story"",""project A"",""rush hour"""
3,Brigitte Li,46,female,to be supplemented
4,Maggie Cheung,39,female,to be supplemented
5,Jet Li,41,male,"""Fist of Legend"",""Once Upon a Time in China"""
2,Gong Li,38,female,"""Farewell My Concubine"",""Lifetimes Living"

文章來源:腳本之家

來源地址:https://www.jb51.net/article/206930.htm

申請創(chuàng)業(yè)報道,分享創(chuàng)業(yè)好點子。點擊此處,共同探討創(chuàng)業(yè)新機遇!

相關(guān)文章

熱門排行

信息推薦