本文主要是介绍python 求excel每列平均值并追加写入到最后一行 读取 修改 表格,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
# -*- encoding: utf-8 -*-
# 读取excel表格
import xlrd
from xlutils.copy import copy## 第一步,读取
# excel表格在哪里
filename = "./students.xls"
workbook = xlrd.open_workbook(filename)
sheetnames = workbook.sheet_names()
sheetwork = workbook.sheet_by_name(sheetnames[0])# 行数
nrows = sheetwork.nrows
# 列数
ncols = sheetwork.ncols
print("nrows", nrows)
print("ncols", ncols)allData_list = []
for i in range(nrows):new_row_list = []for j in range(ncols):data = sheetwork.cell_value(i, j)new_row_list.append(data)allData_list.append(new_row_list)print(allData_list)# 第二步,求平均
# 首先得知道你从哪里开始计数
# 参数初始化
start_r_idx = 1
start_c_idx = 1# 求每列平均
all_avg_per_col = {}for m_col in range(start_c_idx, ncols):one_col_sum = 0for m_row in range(start_r_idx, nrows):one_col_sum += allData_list[m_row][m_col]one_col_avg = one_col_sum / (nrows - start_r_idx)print(one_col_avg)all_avg_per_col[m_col] = one_col_avgprint(all_avg_per_col)# 第三步,输出保存# 找到需要更该的xls
# 对数据表格进行复制
old_content = copy(workbook)
# 定位到Sheet1表
ws = old_content.get_sheet(0)
# 在sheet1表中写入内容
ws.write(nrows, 0, 'avg')
for m_col in range(start_c_idx, ncols):"""对excel进行修改/添加内容"""ws.write(nrows, m_col, all_avg_per_col[m_col])# 对修改后的内容进行保存
old_content.save(filename)
https://www.cnblogs.com/Teachertao/p/10426265.html
https://www.bilibili.com/video/av838723734
这篇关于python 求excel每列平均值并追加写入到最后一行 读取 修改 表格的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!