如何将MySQL查询的输出保存到MS Excel工作表中?
即使只能将数据存储在.txt
文件中,也可以。
如何将MySQL查询的输出保存到MS Excel工作表中?
即使只能将数据存储在.txt
文件中,也可以。
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 application 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 /tmp/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'
或者您可以尝试通过客户端获取输出:
您可以尝试从本地客户端执行查询,并将输出重定向到本地文件目标:
mysql -user -pass -e "select cols from table where cols not null" > /tmp/output
INTO OUTFILE 'output.csv'
或INTO OUTFILE './output.csv'
的内容,它将把输出文件存储到由show variables like 'datadir';
指定的目录中。ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
,你仍然可以将文件保存在/var/lib/mysql-files/
(Debian)中,并在之后将其移动到所需位置。 - maulinglawns您可以编写以下代码来实现此任务:
SELECT ... FROM ... WHERE ...
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'
它将结果导出到CSV文件,然后将其导出到Excel表格中。