问题遇到的现象和发生背景
计算numbers.xlsx中的每一行的平均值,并添加到numbers.xlsx
表中最右侧的列中。计算每一列的数据之和,添加在每一列的最下方。
最终计算行和列的总和,填写在右下角的单元格中。
问题相关代码,请勿粘贴截图
import openpyxl
fn = r'C:\Users\HP\Desktop\numbers.xlsx'
wb = openpyxl.load_workbook(fn)
计算numbers.xlsx中的每一行的平均值,并添加到numbers.xlsx
表中最右侧的列中。计算每一列的数据之和,添加在每一列的最下方。
最终计算行和列的总和,填写在右下角的单元格中。
import openpyxl
fn = r'C:\Users\HP\Desktop\numbers.xlsx'
wb = openpyxl.load_workbook(fn)
看了楼上的大神写法,好自卑啊。但好歹写出来了,还是贴出来吧~
import openpyxl
fn = r'test.xlsx'
wb = openpyxl.load_workbook(fn)
sheet = wb['Sheet1']
data = [[0] * sheet.max_column for _ in range(sheet.max_row)]
total_sum = 0
total_col_sum = [0 for _ in range(sheet.max_row)]
total_row_sum = [0 for _ in range(sheet.max_column)]
for i in range(1, sheet.max_row + 1):
for j in range(1, sheet.max_column + 1):
excel_value = sheet.cell(i, j).value
data[i - 1][j - 1] = excel_value
total_sum += excel_value
total_col_sum[j - 1] += excel_value
total_row_sum[i - 1] += excel_value
# print(excel_value)
wb.close()
print('row=' + str(total_row_sum))
print('col=' + str(total_col_sum))
print('total_sum=' + str(total_sum))
new_data = data.copy()
new_data.append(total_col_sum)
for i in range(len(new_data)):
if i == len(new_data) - 1:
new_data[i].append(total_sum)
else:
new_data[i].append(total_row_sum[i] / sheet.max_row)
print(new_data)
new_file = 'output.xlsx'
wb = openpyxl.Workbook()
ws = wb.active
for i in range(1, len(new_data[1]) + 1):
for j in range(1, len(new_data) + 1):
ws.cell(i, j).value = new_data[i - 1][j - 1]
wb.save(new_file)
wb.close()