使用Python3对Excel进行修改

本列展示如何在Excel中自动的计算值以及如何自动的添加表格

#别名
import openpyxl as xl
from openpyxl.chart import BarChart,Reference
#加载对象
wb = xl.load_workbook('transactions.xlsx')
sheet = wb['Sheet1']    #excel中的下面的Sheet1
cell = sheet['a1']      #a1为列表
cell = sheet.cell(1,1)  #取第一个表格的值
# print(cell.value)
# print(sheet.max_row)
for row in range(2,sheet.max_row + 1):
    # print(row)
    cell = sheet.cell(row,3)	#取第三列的值
    # print(cell.value)
    cor_price = cell.value * 8
    cor_price_call = sheet.cell(row,4)	#计算完的值显示在第四列
    cor_price_call.value = cor_price

values = Reference(sheet,min_row=2,
          max_row=sheet.max_row,
          min_col=4,	#需要显示的表格的行
          max_col=4)	#需要显示的表格的列

chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart,'a5')
wb.save('transactions1.xlsx')

在这里插入图片描述
如果要处理成千的表格,就需要去定义一个模块和函数

#xmlcl.py
#别名
import openpyxl as xl
from openpyxl.chart import BarChart,Reference
#加载对象
def con_f(filename):
    wb = xl.load_workbook(filename)
    sheet = wb['Sheet1']    #excel中的下面的Sheet1
    # print(cell.value)
    # print(sheet.max_row)
    for row in range(2,sheet.max_row + 1):
        # print(row)
        cell = sheet.cell(row,3)
        # print(cell.value)
        cor_price = cell.value * 8
        cor_price_call = sheet.cell(row,4)
        cor_price_call.value = cor_price

    values = Reference(sheet,min_row=2,
              max_row=sheet.max_row,
              min_col=3,
              max_col=3)

    chart = BarChart()
    chart.add_data(values)
    sheet.add_chart(chart,'a5')
    wb.save(filename)
#2.py
from xmlcl import con_f
con_f('transactions.xlsx')
发布了67 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44902875/article/details/105314430