1. 程式人生 > >python程式設計快速上手 第12章實踐專案答案

python程式設計快速上手 第12章實踐專案答案

12.1乘法表

建立程式multiplicationTable.py,從命令列接受數字N,在一個Excel電子表格中建立一個NxN的乘法表

import openpyxl
from openpyxl.utils import get_column_letter
wb = openpyxl.Workbook()
sheet = wb.active
str1 = input('請輸入一個整數:')
for i in range(1,int(str1)):
    for j in range(1,int(str1)):
        sheet[get_column_letter(i)+str(j)] = i*j
wb.save('multiplication.xlsx'
)

12.2空行插入程式

建立一個程式blankRowInserter.py,它接受兩個整數和一個檔名字串作為命令列引數。我們將第一個整數稱為N,第二個整數稱為M。程式應該從第N行開始,在電子表格中插入M個空行

import openpyxl
from openpyxl.utils import get_column_letter
wb = openpyxl.load_workbook('multiplication.xlsx')
sheet = wb.active
m = input('從第幾行開始插入空行(請輸入一個整數)')
n = input('一共空幾行(請輸入一個整數)')
for 
i in range(1,sheet.max_column+1): for j in range(sheet.max_row,int(m)-1,-1): sheet[get_column_letter(i)+str(j+int(n))]=sheet[get_column_letter(i)+str(j)].value for i in range(1,sheet.max_column+1): for j in range(int(m),int(m)+int(n)): sheet[get_column_letter(i)+str(j)] = None
wb.save('multiplication_copy.xlsx')

12.3電子表格單元格翻轉程式

編寫一個程式,翻轉電子表格中行和列的單元格。例如,第5行第3列的值將出現在第3行第5列

import openpyxl
from openpyxl.utils import get_column_letter
wb = openpyxl.load_workbook('12_13_3.xlsx')
sheet = wb['Sheet1']
if  sheet.max_row > sheet.max_column:
    length = sheet.max_row
else:
    length = sheet.max_column

for i in range(1,length+1):
    for j in range(1,length+1):
        if i == j or i>j:
            continue
        else:
            temp =sheet[get_column_letter(i) + str(j)].value
            sheet[get_column_letter(i) + str(j)] = sheet[get_column_letter(j) + str(i)].value
            sheet[get_column_letter(j) + str(i)] = temp
            print(str(sheet[get_column_letter(i) + str(j)].value)+'    '+str(sheet[get_column_letter(j) + str(i)].value))
wb.save('12_13_3copy.xlsx')