使用 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.')
我得到的结果只是 sheet 上的最后一个单元格值,而不是整列。这是它打印的内容:
2017-02-13 16:15:00
0.0022
-0.0021
-1.0476190476190477
Done.
这是因为您覆盖了日期、伽玛等所有变量。所以在循环结束时,你将只有最后一个数据,所以它只写最后一行。
我希望下面的代码能工作
导入 openpyxl、pprint
wb = openpyxl.load_workbook('/Users/sarahporgess/Desktop/SSA.xlsx')
sheet = wb.get_sheet_by_name('SSA')
resultFile = open('SSS.csv', 'w')
对于范围 (2,sheet.max_row+1) 中的行:
对于 "ABC" 中的列:
#PROBLEM 1-只打印出一个值,而不是列
日期 = sheet['A' +str(row)].value
伽玛 = sheet['B' +str(row)].value
theta = sheet['C' +str(row)].value
比率 = 浮点数(伽玛)/浮点数(θ)
resultFile.write(pprint.pformat(日期))
resultFile.write(pprint.pformat(伽玛))
resultFile.write(pprint.pformat(θ))<br>
resultFile.write( pprint.pformat(比率))
打印(比例)
sheet['D1']=比率
resultFile.close()
打印('Done.')
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.')
我得到的结果只是 sheet 上的最后一个单元格值,而不是整列。这是它打印的内容:
2017-02-13 16:15:00
0.0022
-0.0021
-1.0476190476190477
Done.
这是因为您覆盖了日期、伽玛等所有变量。所以在循环结束时,你将只有最后一个数据,所以它只写最后一行。
我希望下面的代码能工作
导入 openpyxl、pprint
wb = openpyxl.load_workbook('/Users/sarahporgess/Desktop/SSA.xlsx')
sheet = wb.get_sheet_by_name('SSA')
resultFile = open('SSS.csv', 'w')
对于范围 (2,sheet.max_row+1) 中的行:
对于 "ABC" 中的列:
#PROBLEM 1-只打印出一个值,而不是列
日期 = sheet['A' +str(row)].value
伽玛 = sheet['B' +str(row)].value
theta = sheet['C' +str(row)].value
比率 = 浮点数(伽玛)/浮点数(θ)
resultFile.write(pprint.pformat(日期))
resultFile.write(pprint.pformat(伽玛))
resultFile.write(pprint.pformat(θ))<br>
resultFile.write( pprint.pformat(比率))
打印(比例)
sheet['D1']=比率
resultFile.close()
打印('Done.')