It is possible export sqlite3 table to csv or xls format? I'm using python 2.7 and sqlite3.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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)
Hope this helps!
Edit: 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)
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.
回答2:
Yes.Read here sqlitebrowser
- Import and export records as text
- Import and export tables from/to CSV files
- Import and export databases from/to SQL dump files
回答3:
External programs: see documentation for sqlite3 for details. You can do it from shell/command line.
On the fly: csv module will help you to handle CSV file format correctly