如何在python中使用xlsxwriter将数据从SQLITE导入excel

时间:2013-09-07 21:53:10

标签: python excel sqlite xlsxwriter

import sqlite3
from xlsxwriter.workbook import Workbook
workbook = Workbook('output2.xlsx')
worksheet = workbook.add_worksheet()

conn=sqlite3.connect('test.sqlite')
c=conn.cursor()
c.execute("select * from abc")
mysel=c.execute("select * from abc ")
for row in mysel:
 print row
 worksheet.write(0, 0, row[0])
workbook.close()

这里是SQLITE数据库表的布局

id  sno
1   100
2   200
3   300
4   400

with worksheet.write(0,0,row [0])我在excel文件的第一个单元格中输出 4

with worksheet.write(0,0,row [1])我在excel文件的第一个单元格中输出 400

无法找出 FOR LOOP 问题。

请帮助

2 个答案:

答案 0 :(得分:3)

import sqlite3
from xlsxwriter.workbook import Workbook
workbook = Workbook('output2.xlsx')
worksheet = workbook.add_worksheet()

conn=sqlite3.connect('test.sqlite')
c=conn.cursor()
c.execute("select * from abc")
mysel=c.execute("select * from abc ")
for i, row in enumerate(mysel):
    for j, value in enumerate(row):
        worksheet.write(i, j, row[j])
workbook.close()

答案 1 :(得分:2)

你的循环很好,除了你将每行数据写入同一个单元格。我不知道xlswriter,但我猜第一个和第二个参数是行和列。如果要将所有数据写为表,则需要在每次写操作时更改这些数据。

这样的东西(未经测试)?

import sqlite3
from xlsxwriter.workbook import Workbook
workbook = Workbook('output2.xlsx')
worksheet = workbook.add_worksheet()

conn=sqlite3.connect('test.sqlite')
c=conn.cursor()
c.execute("select * from abc")
mysel=c.execute("select * from abc ")
for i, row in enumerate(mysel):
    print row
    worksheet.write(i, 0, row[0])
    worksheet.write(i, 1, row[1])
workbook.close()

要处理多个列,您可以执行此操作

import sqlite3
from xlsxwriter.workbook import Workbook
workbook = Workbook('output2.xlsx')
worksheet = workbook.add_worksheet()

conn=sqlite3.connect('test.sqlite')
c=conn.cursor()
c.execute("select * from abc")
mysel=c.execute("select * from abc ")
for i, row in enumerate(mysel):
    for j, value in enumerate(row):
        worksheet.write(i, j, value)
workbook.close()