我是Python初学者,我正在尝试创建一个脚本来汇总excel spereadsheet列中的所有值,然后编写此值。我正在使用xlrd和xlwt python包。它适用于第一列,但它不适用于第二列,直到最后一列。这是我的代码。希望有人可以帮助我。
import xlwt
import xlrd
workbook_page = xlrd.open_workbook('page_level.xlsx')
worksheet_page = workbook_page.sheet_by_name('Daily External Referrers')
num_rows = worksheet_page.nrows - 1
curr_row = 0`
num_cols = worksheet_page.ncols - 1`
curr_col = 1
soma = 0
while curr_col < num_cols:
curr_col = curr_col + 1
while curr_row < num_rows:
curr_row = curr_row + 1
row = (worksheet_page.cell_value(curr_row, curr_col))
if isinstance (row, float):
soma = soma + row
else:
pass
worksheet_page.write(num_rows+1, curr_col, soma)
worksheet_page.save('page_level.xlsx')
答案 0 :(得分:0)
我认为您不能直接编辑您正在使用xlrd阅读的Excel工作簿,您必须将其复制到新工作簿并进行编辑。
只是一个prefence,但我也会使用for循环而不是while循环只是为了方便。
我目前无法测试它,但也许尝试更像这样的东西?
import xlwt, xlrd
from xlutils.copy import copy
read_workbook_page = xlrd.open_workbook('page_level.xlsx')
workbook_page = copy(read_workbook_page)
worksheet_page = workbook_page.sheet_by_name('Daily External Referrers')
num_rows = worksheet_page.nrows - 1
num_cols = worksheet_page.ncols - 1
for row in range(num_rows):
column_sum = 0
for column in range(1, num_cols):
column_sum += worksheet_page.cell_value( row, column )
worksheet_page.write(row, num_cols, column_sum )
worksheet_page.save('page_level.xlsx')