Python 2.7 如何使用python脚本将Mysql表数据导出到excel文件?
我一直在尝试使用Python2.7.8将该数据从表导出到excel文件,但没有成功。请帮帮我。我的要求是从表中导出数据并将其存储在本地(windows C驱动器)Python 2.7 如何使用python脚本将Mysql表数据导出到excel文件?,python-2.7,Python 2.7,我一直在尝试使用Python2.7.8将该数据从表导出到excel文件,但没有成功。请帮帮我。我的要求是从表中导出数据并将其存储在本地(windows C驱动器) 这可能是不用Python就可以轻松完成的事情,但这里有一个框架结构。注意,这会写入.csv文件,而不是Excel文件。您可以使用xlwt库来完成后者 请注意,您需要先pip安装MySQL-python,这通常是无痛的,但也很简单 编辑-这应该会将其写入Excel,但我对xlwt不是很熟悉,而且我还没有测试过这段代码 import My
这可能是不用Python就可以轻松完成的事情,但这里有一个框架结构。注意,这会写入.csv文件,而不是Excel文件。您可以使用
xlwt
库来完成后者
请注意,您需要先pip安装MySQL-python
,这通常是无痛的,但也很简单
编辑-这应该会将其写入Excel,但我对xlwt
不是很熟悉,而且我还没有测试过这段代码
import MySQLdb
from xlsxwriter.workbook import Workbook
user = '' # your username
passwd = '' # your password
host = '' # your host
db = '' # database where your table is stored
table = '' # table you want to save
con = MySQLdb.connect(user=user, passwd=passwd, host=host, db=db)
cursor = con.cursor()
query = "SELECT * FROM %s;" % table
cursor.execute(query)
workbook = Workbook('outfile.xlsx')
sheet = workbook.add_worksheet()
for r, row in enumerate(cursor.fetchall()):
for c, col in enumerate(row):
sheet.write(r, c, col)
他写道:
import mysql.connector
from openpyxl import Workbook
def main():
# Connect to DB -----------------------------------------------------------
db = mysql.connector.connect( user='root', password='', host='127.0.0.1')
cur = db.cursor()
# Create table ------------------------------------------------------------
database = 'test_database'
SQL = 'CREATE DATABASE IF NOT EXISTS ' + database + ';'
cur.execute(SQL)
db.commit()
SQL = 'USE ' + database + ';'
cur.execute(SQL)
# Create car data ---------------------------------------------------------
cars_table_name = 'cars'
SQL = (
'CREATE TABLE IF NOT EXISTS ' + cars_table_name +
'('
' model_year YEAR, '
' manufacturer VARCHAR(40), '
' product VARCHAR(40)'
');')
cur.execute(SQL)
db.commit()
# Python list of dictionaries
# More info at:
# https://stackoverflow.com/questions/8653516/python-list-of-dictionaries-search
car_data = [
{ 'model_year': '2010', 'manufacturer': 'Toyota', 'product': 'Prius' },
{ 'model_year': '2010', 'manufacturer': 'Honda', 'product': 'CR-V' },
{ 'model_year': '1998', 'manufacturer': 'Honda', 'product': 'Civic' },
{ 'model_year': '1997', 'manufacturer': 'Ford', 'product': 'F-150' },
{ 'model_year': '2017', 'manufacturer': 'Tesla', 'product': 'Model 3' },
]
# Code adapted from:
# https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html
add_cars = ('INSERT INTO ' + cars_table_name + ' (model_year, manufacturer, product) '
' VALUES (%(model_year)s, %(manufacturer)s, %(product)s)')
for car_datum in car_data:
cur.execute(add_cars, car_datum);
db.commit()
# Create manufacturer data -----------------------------------------------
manufacturer_table_name = 'manufacturer'
SQL = (
'CREATE TABLE IF NOT EXISTS ' + manufacturer_table_name +
'('
' name VARCHAR(40), '
' headquarters VARCHAR(40), '
' number_of_employees INT, '
' website VARCHAR(40)'
');')
cur.execute(SQL)
db.commit()
add_manufacturer = (
'INSERT INTO ' + manufacturer_table_name +
' (name, headquarters, number_of_employees, website) '
' VALUES (%s, %s, %s, %s)')
# Python list of lists
# More info at:
# https://stackoverflow.com/questions/18449360/access-item-in-a-list-of-lists
# Data from:
# https://en.wikipedia.org/wiki/Toyota
# Honda data from: https://en.wikipedia.org/wiki/Honda
# Ford data from: https://en.wikipedia.org/wiki/Ford
# Tesla data from: https://en.wikipedia.org/wiki/Tesla,_Inc.
manufacture_data = [
[ 'Toyota', 'Toyota, Aichi, Japan', '364445', 'http://toyota-global.com/' ],
[ 'Honda', 'Minato, Tokyo, Japan', '208399', 'http://world.honda.com/' ],
[ 'Ford', 'Dearborn, Michigan, U.S.', '201000', 'http://www.ford.com/' ],
[ 'Tesla, Inc.', 'Palo Alto, California, US', '33000', 'http://www.tesla.com/' ],
]
for manufacturer_datum in manufacture_data:
cur.execute(add_manufacturer, manufacturer_datum);
db.commit()
# Create Excel (.xlsx) file -----------------------------------------------
wb = Workbook()
SQL = 'SELECT * from '+ cars_table_name + ';'
cur.execute(SQL)
results = cur.fetchall()
ws = wb.create_sheet(0)
ws.title = cars_table_name
ws.append(cur.column_names)
for row in results:
ws.append(row)
SQL = 'SELECT * from '+ manufacturer_table_name + ';'
cur.execute(SQL)
results = cur.fetchall()
ws = wb.create_sheet(0)
ws.title = manufacturer_table_name
ws.append(cur.column_names)
for row in results:
ws.append(row)
workbook_name = "test_workbook"
wb.save(workbook_name + ".xlsx")
# Remove tables and database ----------------------------------------------
SQL = 'DROP TABLE ' + manufacturer_table_name + ';'
cur.execute(SQL)
db.commit()
SQL = 'DROP TABLE ' + cars_table_name + ';'
cur.execute(SQL)
db.commit()
SQL = 'DROP DATABASE ' + database + ';'
cur.execute(SQL)
db.commit()
if __name__ =='__main__':main()
非常感谢你。这对我来说很有效,但我的要求是将表格数据导出到Excel文件,我已经为其编写了代码。请帮帮我,我已经试过了。如果有帮助,请向上投票和/或选择我的答案。@jgysland:我尝试了你的代码,但看不到任何导出的文件:(你知道为什么吗?@ihue:你找不到该文件?你在执行脚本的同一目录中查找了吗?请确保关闭工作簿,否则它可能不会保存它。最后是“workbook.close()”。添加此选项可以为我保存它:)
import MySQLdb
from xlsxwriter.workbook import Workbook
user = '' # your username
passwd = '' # your password
host = '' # your host
db = '' # database where your table is stored
table = '' # table you want to save
con = MySQLdb.connect(user=user, passwd=passwd, host=host, db=db)
cursor = con.cursor()
query = "SELECT * FROM %s;" % table
cursor.execute(query)
workbook = Workbook('outfile.xlsx')
sheet = workbook.add_worksheet()
for r, row in enumerate(cursor.fetchall()):
for c, col in enumerate(row):
sheet.write(r, c, col)
import mysql.connector
from openpyxl import Workbook
def main():
# Connect to DB -----------------------------------------------------------
db = mysql.connector.connect( user='root', password='', host='127.0.0.1')
cur = db.cursor()
# Create table ------------------------------------------------------------
database = 'test_database'
SQL = 'CREATE DATABASE IF NOT EXISTS ' + database + ';'
cur.execute(SQL)
db.commit()
SQL = 'USE ' + database + ';'
cur.execute(SQL)
# Create car data ---------------------------------------------------------
cars_table_name = 'cars'
SQL = (
'CREATE TABLE IF NOT EXISTS ' + cars_table_name +
'('
' model_year YEAR, '
' manufacturer VARCHAR(40), '
' product VARCHAR(40)'
');')
cur.execute(SQL)
db.commit()
# Python list of dictionaries
# More info at:
# https://stackoverflow.com/questions/8653516/python-list-of-dictionaries-search
car_data = [
{ 'model_year': '2010', 'manufacturer': 'Toyota', 'product': 'Prius' },
{ 'model_year': '2010', 'manufacturer': 'Honda', 'product': 'CR-V' },
{ 'model_year': '1998', 'manufacturer': 'Honda', 'product': 'Civic' },
{ 'model_year': '1997', 'manufacturer': 'Ford', 'product': 'F-150' },
{ 'model_year': '2017', 'manufacturer': 'Tesla', 'product': 'Model 3' },
]
# Code adapted from:
# https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html
add_cars = ('INSERT INTO ' + cars_table_name + ' (model_year, manufacturer, product) '
' VALUES (%(model_year)s, %(manufacturer)s, %(product)s)')
for car_datum in car_data:
cur.execute(add_cars, car_datum);
db.commit()
# Create manufacturer data -----------------------------------------------
manufacturer_table_name = 'manufacturer'
SQL = (
'CREATE TABLE IF NOT EXISTS ' + manufacturer_table_name +
'('
' name VARCHAR(40), '
' headquarters VARCHAR(40), '
' number_of_employees INT, '
' website VARCHAR(40)'
');')
cur.execute(SQL)
db.commit()
add_manufacturer = (
'INSERT INTO ' + manufacturer_table_name +
' (name, headquarters, number_of_employees, website) '
' VALUES (%s, %s, %s, %s)')
# Python list of lists
# More info at:
# https://stackoverflow.com/questions/18449360/access-item-in-a-list-of-lists
# Data from:
# https://en.wikipedia.org/wiki/Toyota
# Honda data from: https://en.wikipedia.org/wiki/Honda
# Ford data from: https://en.wikipedia.org/wiki/Ford
# Tesla data from: https://en.wikipedia.org/wiki/Tesla,_Inc.
manufacture_data = [
[ 'Toyota', 'Toyota, Aichi, Japan', '364445', 'http://toyota-global.com/' ],
[ 'Honda', 'Minato, Tokyo, Japan', '208399', 'http://world.honda.com/' ],
[ 'Ford', 'Dearborn, Michigan, U.S.', '201000', 'http://www.ford.com/' ],
[ 'Tesla, Inc.', 'Palo Alto, California, US', '33000', 'http://www.tesla.com/' ],
]
for manufacturer_datum in manufacture_data:
cur.execute(add_manufacturer, manufacturer_datum);
db.commit()
# Create Excel (.xlsx) file -----------------------------------------------
wb = Workbook()
SQL = 'SELECT * from '+ cars_table_name + ';'
cur.execute(SQL)
results = cur.fetchall()
ws = wb.create_sheet(0)
ws.title = cars_table_name
ws.append(cur.column_names)
for row in results:
ws.append(row)
SQL = 'SELECT * from '+ manufacturer_table_name + ';'
cur.execute(SQL)
results = cur.fetchall()
ws = wb.create_sheet(0)
ws.title = manufacturer_table_name
ws.append(cur.column_names)
for row in results:
ws.append(row)
workbook_name = "test_workbook"
wb.save(workbook_name + ".xlsx")
# Remove tables and database ----------------------------------------------
SQL = 'DROP TABLE ' + manufacturer_table_name + ';'
cur.execute(SQL)
db.commit()
SQL = 'DROP TABLE ' + cars_table_name + ';'
cur.execute(SQL)
db.commit()
SQL = 'DROP DATABASE ' + database + ';'
cur.execute(SQL)
db.commit()
if __name__ =='__main__':main()