2017-07-21 67 views
1

我對python很陌生,並試圖處理一個項目,該項目需要我從SQL(.db)數據庫中提取數據並將該數據輸出到excel文件中。閱讀Sql數據庫和輸出到Excel中的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

一個是從模塊訪問數據庫 任何幫助表示讚賞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() 
+0

大多數數據庫可以直接向CSV文件寫入查詢,該文件可以導入到Excel中。 – jordanm

回答

0

你需要改變查詢如下:

的DbCommand = 「SELECT DISTINCT [環境] FROM」 +一[X] [0]

這將返回您正在尋找的唯一值

0

是否要從數據庫列中刪除重複項並將其存儲在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)