有可能将表sqlite3表导出到csv或类似的?

时间:2010-11-24 07:28:14

标签: python sqlite

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

3 个答案:

答案 0 :(得分:9)

我使用来自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中使用标题,则快速方法是在从数据库写入数据之前手动添加另一行,例如:

# 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方言并将其传递给编写器,如下所示:

csv.register_dialect('pipeseparated', delimiter = '|')

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

这是您可以使用自定义方言的a list of the various formatting parameters

答案 1 :(得分:1)

是。点击这里sqlitebrowser

  • 将记录导入和导出为文本
  • 从/向CSV文件导入和导出表格
  • 从/向SQL转储文件导入和导出数据库

答案 2 :(得分:0)

外部程序:有关详细信息,请参阅sqlite3的文档。您可以从shell /命令行执行此操作。

动态: csv module将帮助您正确处理CSV文件格式