【问题标题】:Importing mysql table in excel在excel中导入mysql表
【发布时间】:2014-09-18 02:00:10
【问题描述】:

我是 python 中的菜鸟,但我需要在 python 中使用 xlwt 将 MySQL 表导出到 .xls 文件中。我使用此处的示例成功导出了表格

http://ryrobes.com/featured-articles/using-xlwt-and-python-to-export-an-oracle-dataset-to-excel-python-simple-etl-part-2/

但是如果 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


【解决方案1】:

表格按字母顺序或升序排列,如果您想要有条理的顺序,请改用行。

【讨论】:

  • 这也将解决顺序问题,但即使使用行我似乎也无法获得列名。
猜你喜欢
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2013-06-15
  • 2011-06-23
相关资源
最近更新 更多