使用python

时间:2017-06-28 17:41:52

标签: python excel openpyxl

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.

1 个答案:

答案 0 :(得分:0)

这是因为你要覆盖所有变量,如日期,伽玛等。所以在循环结束时,你将只有最后一个数据,所以它只写最后一行。

我希望下面的代码能够正常工作 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.')