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')

猜你喜欢

转载自blog.csdn.net/u014221647/article/details/81018455
今日推荐