Excel-乘法表

Excel-乘法表

@(Python)[python]

乘法表

创建程序multiplicationTable.py,从命令行接受数字N,在一个Excel 电子表格中创建一个N×N 的乘法表。例如,如果这样执行程序:
py multiplicationTable.py 6
它应该创建一个图所示的电子表格。
这里写图片描述
行1 和列A 应该用做标签,应该使用粗体。

from trace import Trace

import openpyxl
import sys
from openpyxl.styles import Font

# script first argument
max_num = int(sys.argv[1])

# init excel info
wb = openpyxl.Workbook()
sheet = wb.get_active_sheet()
sheet.title = 'multiplicationTable'

font = Font(bold=True)

# init first row...1 2 3 4 ...
for column in range(1, max_num + 1):
    multiplier_cell = sheet.cell(row=1, column=column + 1)
    multiplier_cell.font = font
    multiplier_cell.value = column

# init first column...1 2 3 4 ...
for row in range(1, max_num + 1):
    multiplicand_cell = sheet.cell(row=row + 1, column=1)
    multiplicand_cell.font = font
    multiplicand_cell.value = row


# Solve-by dynamic programming
for row in range(1, max_num + 1):
    for column in range(1, max_num + 1):
        # each column, first row
        multiplier_cell = sheet.cell(row=1, column=column + 1)
        # each row, first column
        multiplicand_cell = sheet.cell(row=row + 1, column=1)
        # result[i][j] = result[1][i] * result[i][1]
        result_cell = sheet.cell(row=row + 1, column=column + 1)
        multiplier_value = multiplier_cell.value
        multiplicand_value = multiplicand_cell.value
        result_cell.value = multiplier_value * multiplicand_value
wb.save('multiplicationTable.xlsx')

猜你喜欢

转载自blog.csdn.net/q547550831/article/details/71082180