我是python
的新手,正在尝试处理一个需要我从SQL(.db)
数据库中提取数据并将这些数据输出到excel文件中的项目。
我的数据库文件有很多数据,但我设法打印出的结构如下
Run ID | Environment
1 52
2 52
3 52
4 52
5 72
6 72
7 72
8 72
....
现在,我需要能够将这些值输出到excel电子表格中,
52|72|92|112|132
下面是我当前的代码,它允许我输出
52|52|52|52|72|72|72|72 |72
A是模块access数据库中的c.fetchall()
,如有任何帮助,不胜感激
Access_Database_Module.Access_Database(DB)
x = 2
DBcommand = "SELECT * FROM " + a[x][0]
print(a[x][0])
c.execute(DBcommand)
y = c.fetchall()
x = y
workbook = xls.Workbook('Environment.xlsx')
worksheet = workbook.add_worksheet('Environment Direction')
rowNum = 0
colNum = 1
workbook = xls.Workbook('Environment.xlsx')
worksheet = workbook.add_worksheet('Environment Direction')
for item in y:
while colNum == colNum + 1 :
colNum
worksheet.write(rowNum, colNum, item[14])
colNum += 1
workbook.close()
发布于 2017-07-21 11:56:02
您需要更改查询,如下所示:
DBcommand = "SELECT distinct Environment FROM“+ ax
这将返回您要查找的唯一值
发布于 2017-07-21 11:57:17
是否要从数据库列中删除重复项并将其存储在excel中?如果是这样的话,下面的代码可能会对你有所帮助。
import pandas as pd
import sqlite3
# get DB connection
con = sqlite3.connect("your DB connection")
# Read sqlite query results into a pandas DataFrame
df = pd.read_sql_query("SELECT * from yourDB", con)
# verify that result of SQL query is stored in the dataframe
print(df.head())
con.close()
# if you want to remove duplicate based on particular column then do this
df.drop_duplicates(subset=[column_name],inplace=True)
# else do this
df.drop_duplicates(inplace=True)
# export to Excel file
df.to_excel("filename.xlsx",index=False)
https://stackoverflow.com/questions/45228504
复制相似问题