可以将表 sqlite3 表导出到 csv 或类似的吗? [英] It is possible export table sqlite3 table to csv or similiar?

查看:41
本文介绍了可以将表 sqlite3 表导出到 csv 或类似的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

It is possible export sqlite3 table to csv or xls format? I'm using python 2.7 and sqlite3.

推荐答案

我使用来自 文档;它只是将整个表格导出到 CSV 文件:

I knocked this very basic script together using a slightly modified example class from the docs; it simply exports an entire table to a CSV file:

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

If you want headers in the CSV, the quick way is to manually add another row before you write the data from the database, e.g:

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

Edit 2: To output pipe-separated columns, register a custom CSV dialect and pass that into the writer, like so:

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

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

这是各种格式参数的列表,您可以与自定义方言一起使用.

Here's a list of the various formatting parameters you can use with a custom dialect.

这篇关于可以将表 sqlite3 表导出到 csv 或类似的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆