簡體   English   中英

使用python編寫Excel列

[英]writing an excel column using python

import openpyxl, pprint

wb = openpyxl.load_workbook('/Users/sarahporgess/Desktop/SSA.xlsx')
sheet = wb.get_sheet_by_name('SSA')

for row in range(2,sheet.max_row+1):
    for column in "ABC":
        #PROBLEM 1-only printing out one value, not the column
        date = sheet['A' +str(row)].value
        gamma = sheet['B' +str(row)].value
        theta = sheet['C' +str(row)].value

print(date)
print(gamma)
print(theta)

ratio = float(gamma)/float(theta)
print(ratio)
sheet['D1']=ratio


#3. Write to new sheet  
resultFile = open('SSS.csv', 'w')

#PROBLEM 2- The format of the file is off. 
resultFile.write(pprint.pformat(date))

resultFile.write(pprint.pformat(gamma))
resultFile.write(pprint.pformat(theta))    
resultFile.write( pprint.pformat(ratio))    
resultFile.close()
print('Done.')

我得到的結果只是工作表上的最后一個單元格值,而不是整列。 這是它打印的內容:

2017-02-13 16:15:00

0.0022

-0.0021

-1.0476190476190477

Done.

這是因為您正在覆蓋所有變量,如date,gamma等。 因此,在循環結束時,您將僅擁有最后一個數據,因此僅寫入了最后一行。

我希望下面的代碼可以工作
import openpyxl, pprint wb = openpyxl.load_workbook('/Users/sarahporgess/Desktop/SSA.xlsx') sheet = wb.get_sheet_by_name('SSA') resultFile = open('SSS.csv', 'w') for row in range(2,sheet.max_row+1): for column in "ABC": #PROBLEM 1-only printing out one value, not the column date = sheet['A' +str(row)].value gamma = sheet['B' +str(row)].value theta = sheet['C' +str(row)].value ratio = float(gamma)/float(theta) resultFile.write(pprint.pformat(date)) resultFile.write(pprint.pformat(gamma)) resultFile.write(pprint.pformat(theta))
resultFile.write( pprint.pformat(ratio)) print(ratio) sheet['D1']=ratio resultFile.close() print('Done.')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM