实践出真知,这次我们就通过一些实例来巩固一下用Python的openpyxl模块处理Excel的一些操作吧!
一、乘法表
创建程序,从命令行接收数字N,在一个Excel电子表格中创建一个N×N的乘法表。行1和列A用作标签,应该使用粗体。
# coding=utf-8
import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font
N = int(input('请输入一个数字:'))
wb = openpyxl.Workbook()
sheet = wb.active
fontObj = Font(bold=True)
# 先将第一行和第一列的数据写入,并设置字体样式
for i in range(1, N + 1):
sheet[get_column_letter(i + 1) + str(1)] = i
sheet[get_column_letter(i + 1) + str(1)].font = fontObj
sheet['A' + str(i + 1)] = i
sheet['A' + str(i + 1)].font = fontObj
# 写入其他行的数据
for i in range(2, N + 2):
for j in range(2, N + 2):
sheet.cell(row=i, column=j).value = sheet.cell(row=1, column=j).value * sheet.cell(row=i, column=1).value
# 保存文件
wb.save('D:\\PythonCodes\\multiplicationTable.xlsx')
运行以上程序并在命令行输入8得到的表格为: