【问题标题】:Convert the mysql table details to an Excel (.xls) or comma separated file (.csv) using Python使用 Python 将 mysql 表详细信息转换为 Excel (.xls) 或逗号分隔文件 (.csv)
【发布时间】:2011-01-29 17:38:50
【问题描述】:

我想使用 python 脚本将 mysql 数据库表内容转换为 Excel(.xls) 或逗号分隔文件(csv)...可以吗?谁能帮帮我?

提前致谢, 尼米

【问题讨论】:

    标签: python mysql file csv xlwt


    【解决方案1】:

    安装第三方项目mysqldb 后,您可以轻松读取该表,例如:

    import MySQLdb
    conn = MySQLdb.connect (host = "localhost",
                            user = "testuser",
                            passwd = "testpass",
                            db = "test")
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM thetable")
    while True:
       row = cursor.fetchone()
       if row is None: break
       # here: do something with the row
    

    您当然可以使用 Python 的标准库 csv 模块将每一行写入一个 csv 文件——您只需要在代码开头添加一个 import csv。然后,在cursor.execute之后,可以使用如下代码:

    with open('thefile.csv', 'w') as f:
        writer = csv.writer(f)
        while True:
            row = cursor.fetchone()
            if row is None: break
            writer.writerow(row)
    

    如果您想写入.xls 文件而不是.csv,请参阅第三方模块xlwt。

    【讨论】:

    • 编辑了 xlwt 的 URL 以删除旧版本号 -- 默认是最新版本,可以减少支持团队的磨损:-)
    猜你喜欢
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2014-12-09
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    相关资源
    最近更新 更多