是否可以将sqlite3表导出为csv或xls格式?我正在使用python 2.7和sqlite3。

最佳答案

我使用the docs中经过稍微修改的示例类将这个非常基本的脚本组合在一起;它只是将整个表导出到CSV文件:

import sqlite3
import csv, codecs, cStringIO

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([unicode(s).encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

conn = sqlite3.connect('yourdb.sqlite')

c = conn.cursor()
c.execute('select * from yourtable')

writer = UnicodeWriter(open("export.csv", "wb"))

writer.writerows(c)

希望这可以帮助!

编辑:如果要在CSV中使用 header ,快速的方法是在从数据库写入数据之前手动添加另一行,例如:
# Select whichever rows you want in whatever order you like
c.execute('select id, forename, surname, email from contacts')

writer = UnicodeWriter(open("export.csv", "wb"))

# Make sure the list of column headers you pass in are in the same order as your SELECT
writer.writerow(["ID", "Forename", "Surname", "Email"])
writer.writerows(c)

编辑2:要输出用管道分隔的列,请注册一个自定义CSV方言并将其传递给writer,如下所示:
csv.register_dialect('pipeseparated', delimiter = '|')

writer = UnicodeWriter(open("export.csv", "wb"), dialect='pipeseparated')

这是a list of the various formatting parameters,可以与自定义方言一起使用。

10-06 05:31
查看更多