pythonxlrd中列的问题

2024-10-03 06:30:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个Python初学者,我正在尝试编写一个脚本,将excel spereadsheet的一列中的所有值求和,然后编写这个值。我使用的是xlrd和xlwt python包。它适用于第一个columm,但直到最后一个专栏才适用于第二个columm。这是我的密码。希望有人能帮我。在

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')

Tags: importpagecolxlsxlevelnumrowsrow
1条回答
网友
1楼 · 发布于 2024-10-03 06:30:27

我不认为你可以直接编辑你正在用xlrd阅读的excel工作簿,你必须将它复制到新的工作簿中并进行编辑。在

我也会用循环,而不是简单的循环。在

我现在无法测试,但也许可以试试这样的方法?在

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')

相关问题 更多 >