Sqlite 如何使用 python 将 sqlite 数据 table 列行写入 excel

Sqlite how to write sqlite data table column row into excell using python

您好,我想使用 python 将我的 sqlite 数据插入到 excell 中。我知道如何导入行值,但不知道如何导入 table 列名称。我需要在 excell 的第一行中输出:table 列名,在第二行中:列值等

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

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

输出应该是这样的:

     A    B
   1 id  name
   2 1   Alex
   3 2   Rubick
   4 3   John
   5 4   Mathew

当前输出

1   1 Alex
2   2 Rubick 
3   3 John
4   4 Mathew

这是一个使用 pandas 库的简单解决方案。

import pandas as pd
import sqlite3 as sqlite
connection = sqlite.connect('database/path')
pd.read_sql_query('your sql query', connection).to_excel('path/and/name/of/excel/file/to/be/created') # You could also give it an existing ExcelWriter object

下面是仅使用 sqlite3 的方法: 将 pandas 导入为 pd 将 sqlite3 导入为 sqlite 连接 = sqlite.connect('database/path') 数据 = cursor.execute('select * from users').fetchall() columns_names = [column_tuple[0] column_tuple 在 cursor.description]

将 columns_names 添加到电子表格的第一行,然后遍历数据逐行添加它们。