2017-04-26 176 views
0

我想使用Python打開一個文件並將查詢結果從Oracle中粘貼到特定工作表中。我找到了一種與xlswriter一起使用的方法,但這不是該工作的正確工具。Python openpyxl錯誤

我可以讓我的查詢執行並追加到列表中。結果中我有兩個字符串和整數。我無法將其轉移到Excel文件中。任何幫助都會很棒。

我得到的錯誤是:

line 201, in _bind_value 
    raise ValueError("Cannot convert {0} to Excel".format(value)) 

ValueError: Cannot convert ('20 GA GV-CS-CT-DRY-G90 60xC COIL', 2, 848817, 982875, 1.15793510261929) to Excel 

代碼:

import cx_Oracle 
import openpyxl 

con = cx_Oracle.connect('example', 'example', "example") 
cur = con.cursor() 

heatmap_data = [] 

statement = """ select * from example""" 

cur.arraysize = 2000 
cur.execute(statement) 

for result in cur: 
    heatmap_data.append(result) 

con.close() 

file = "path/Test.xlsx" 

wb = openpyxl.load_workbook(filename=file) 
ws = wb.get_sheet_by_name("Sheet1") 

row = 1 
col = 1 


for rowNum in range(2, len(heatmap_data)): 
    ws.cell(row=row, column=col).value = heatmap_data[rowNum] 
    row =+ 1 

wb.save(file) 

回答

0

解決該問題與下面的代碼:

row = 1 


    for i in (heatmap_data): 
     print(i[0], i[1], i[2], i[3], i[4]) 
     ws.cell(row=row, column=1).value = (i[0]) 
     ws.cell(row=row, column=2).value = (i[1]) 
     ws.cell(row=row, column=3).value = (i[2]) 
     ws.cell(row=row, column=4).value = (i[3]) 
     ws.cell(row=row, column=5).value = (i[4]) 
     row += 1 
+0

並不需要打印()命令。 –

0

也許openpyxl不轉換iterables(這是什麼樣子傳遞)到ws.cell.value

嘗試:
for rowNum, data in enumerate(heatmap_data): ws.cell(row=rowNum + 2, column=col).value = ", ".join(data[rowNum]) # Noticed the range you're choosing skips the first 2 values of your data. # Looks like you're not incrementing the column. Meh. Guess not.

嘿。