【发布时间】:2014-09-18 02:00:10
【问题描述】:
我是 python 中的菜鸟,但我需要在 python 中使用 xlwt 将 MySQL 表导出到 .xls 文件中。我使用此处的示例成功导出了表格
但是如果 MySQL 表中的列多于两列,则 Excel 和 MySQL 中表列的顺序不匹配。
下面是部分代码:
from xlwt import *
import sys
import MySQLdb
table_name='student'
sql_select="SELECT * FROM %s"%table_name
conn1 =MySQLdb.connect(host='localhost',user='root',passwd='',db='test')
cu_select=conn1.cursor(MySQLdb.cursors.DictCursor)
try:
cu_select.execute(sql_select)
except MySQLdb.Error, e:
errInsertSql = "Insert Sql ERROR!! sql is==>%s" %(sql_select)
sys.exit(errInsertSql)
result_set = cu_select.fetchall()'
我尝试打印 result_set,发现不匹配从这里开始。谁能帮帮我。
【问题讨论】:
-
发生这种情况的原因是字典具有随机顺序。由于您的要求相对简单,您可以使用普通光标,即不是 DictCursor。
-
@bernie 谢谢,订单已匹配,但我无法获取列名。
-
列元数据可以取自
cursor.description -
谢谢!现在问题已经解决了。
标签: python mysql excel fetchall