2014-01-21 130 views
65

如何將MySQL查詢的輸出保存到MS Excel工作表?如何將MySQL查詢輸出保存爲excel或.txt文件?

即使只能將數據存儲在.txt文件中,也沒關係。

+0

如果你使用phpMyAdmin,有一個選項導出爲csv或excel ect –

+0

@KrishR我可以在哪裏知道?我對工作臺相當陌生 –

+1

您擁有哪個操作系統版本? Linux還是Windows? –

回答

116

Save MySQL query results into a text or CSV file

MySQL provides an easy mechanism for writing the results of a select statement into a text file on the server. Using extended options of the INTO OUTFILE nomenclature, it is possible to create a comma separated value (CSV) which can be imported into a spreadsheet application such as OpenOffice or Excel or any other applciation which accepts data in CSV format.

Given a query such as

SELECT order_id,product_name,qty FROM orders 

which returns three columns of data, the results can be placed into the file /tmo/orders.txt using the query:

SELECT order_id,product_name,qty FROM orders 
INTO OUTFILE '/tmp/orders.txt' 

This will create a tab-separated file, each row on its own line. To alter this behavior, it is possible to add modifiers to the query:

SELECT order_id,product_name,qty FROM orders 
INTO OUTFILE '/tmp/orders.csv' 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\n' 

In this example, each field will be enclosed in 「double quotes,」 the fields will be separated by commas, and each row will be output on a new line separated by a newline (\n). Sample output of this command would look like:

"1","Tech-Recipes sock puppet","14.95" "2","Tech-Recipes chef's hat","18.95" 

Keep in mind that the output file must not already exist and that the user MySQL is running as has write permissions to the directory MySQL is attempting to write the file to.

語法

SELECT Your_Column_Name 
    FROM Your_Table_Name 
    INTO OUTFILE 'Filename.csv' 
    FIELDS TERMINATED BY ',' 
    ENCLOSED BY '"' 
    LINES TERMINATED BY '\n' 

或者你可以試試這個太

You could try executing the query from the your local client and redirect the output to a local file destination;

Mysql -user -pass -e"select cols from table where cols not null" > /tmp/output 
+3

當你引用其他人的工作時,你必須放置什麼你已經引用了塊引用,以表明它們不是你自己的單詞。 – 2014-08-14 17:33:36

+0

MySQL用戶名不是一個系統用戶名,因此不能通過定義有權訪問任何內容,甚至不能訪問/ tmp。甚至使用mysql用戶標識代替有效用戶標識來推斷寫入權限的意義何在?有沒有辦法繞過這個(我不是說通過創建一個新的系統用戶)。 –

+1

需要注意的是,這會在服務器中創建文件。正如select into的文檔解釋的那樣,您必須使用mysql命令作爲mysql -e「select ...」。 http://dev.mysql.com/doc/refman/5.7/en/select-into.html – jgomo3

4

您可以編寫以下代碼來實現這一任務:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv' 
FIELDS TERMINATED BY '|' 

,並將結果導出爲CSV,然後導出爲Excel工作表。

+4

得到錯誤代碼:1045訪問被拒絕 – user2568374

+0

@ user2568374您的mysql用戶沒有權限寫入您指定的文件夾內。你可以直接從命令行運行:mysql -u USER -pPASSWORD -e「select ... from database.table where ...」> desired/file.txt – mandza

相關問題