12.1乘法表
创建程序multiplicationTable.py,从命令行接受数字N,在一个Excel电子表格中创建一个NxN的乘法表
importopenpyxl
fromopenpyxl.utils importget_column_letter
wb = openpyxl.Workbook()
sheet = wb.active
str1 = input('请输入一个整数:')
fori inrange(1,int(str1)):
forj inrange(1,int(str1)):
sheet[get_column_letter(i)+str(j)] = i*j
wb.save('multiplication.xlsx')
12.2空行插入程序
创建一个程序blankRowInserter.py,它接受两个整数和一个文件名字符串作为命令行参数。我们将第一个整数称为N,第二个整数称为M。程序应该从第N行开始,在电子表格中插入M个空行
importopenpyxl
fromopenpyxl.utils importget_column_letter
wb = openpyxl.load_workbook('multiplication.xlsx')
sheet = wb.active
m = input('从第几行开始插入空行(请输入一个整数):')
n = input('一共空几行(请输入一个整数):')
fori inrange(1,sheet.max_column+1):
forj inrange(sheet.max_row,int(m)-1,-1):
sheet[get_column_letter(i)+str(j+int(n))]=sheet[get_column_letter(i)+str(j)].value
fori inrange(1,sheet.max_column+1):
forj inrange(int(m),int(m)+int(n)):
sheet[get_column_letter(i)+str(j)] = Nonewb.save('multiplication_copy.xlsx')
12.3电子表格单元格翻转程序
编写一个程序,翻转电子表格中行和列的单元格。例如,第5行第3列的值将出现在第3行第5列
importopenpyxl
fromopenpyxl.utils importget_column_letter
wb = openpyxl.load_workbook('12_13_3.xlsx')
sheet = wb['Sheet1']
ifsheet.max_row > sheet.max_column:
length = sheet.max_row
else:
length = sheet.max_column
fori inrange(1,length+1):
forj inrange(1,length+1):
ifi == j ori>j:
continueelse:
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')