It is possible export sqlite3 table to csv or xls format? I'm using python 2.7 and sqlite3.
To copy a table or query to a csv file, use either the \copy command or the COPY command.
Use CSV as the export format. Read each row of your table, jopin the columns using a semicolon ( ; ) and append the line to a text file. EASY.
Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited). Note: The different formats support different feature sets.
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.
Yes.Read here sqlitebrowser
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With