1. 制造乘法表
import openpyxl
from openpyxl.utils import get_column_letter
from sys import argv
# 使用argv获取程序名和变量名,方可使用脚本打开该文件
script, N = argv
# 输入默认是str文件,必须int转换
N = int(N)
wb = openpyxl.Workbook()
sheet = wb['Sheet']
# 注意循环体的i的次数,首先将第一列和第一行的数据赋值
for i in range(1, N+2):
sheet['A'+str(i)] = i-1
sheet[get_column_letter(i)+str(1)] = i-1
# 根据第一行和第一列的数据,相乘得到乘法表格
for i in range(2, N+2):
for j in range(2, N+2):
m = get_column_letter(i)
sheet[m+str(j)] = (sheet[m+str(1)].value)*(sheet['A'+str(j)].value)
sheet['A1'] = None
wb.save('MultiplicationTable.xlsx')
# 可以在函数中写入相应的步骤名称,作为检查
print('Done')
2. 插入空白列或行
该程序尝试了很久,最终发现,原来有现成的模块可以使用
import openpyxl
from openpyxl.utils import get_column_letter,column_index_from_string
import sys
script, M, N = argv
# 在第N行中,插入M个空白行
M = int(M)
N = int(N)
wb = openpyxl.load_workbook('MultiplicationTable.xlsx')
sheet = wb.active
# insert_row(x,y) 在第x行起,插入y个空白行
# 同样应该可以使用insert_column(x,y)
sheet.insert_rows(N , M)
wb.save('insert.xlsx')
3. excel表格中行列互换(有点转置矩阵的意思)
import openpyxl
# get_column_letter 整数转字母 column_index_from_string 字母转整数
from openpyxl.utils import get_column_letter,column_index_from_string
wb = openpyxl.load_workbook('inverter.xlsx')
sheet = wb.active
# 建立中转空字典data用于存储
data = {}
# 读取该矩阵的尺寸
row = sheet.max_row
col = sheet.max_column
for x in range(1, row+1):
for y in range(1, col+1):
# 将矩阵的值依次录入到data中后,将原cell值删除
data[(str(x),str(y))] = sheet[x][y-1].value
sheet[x][y-1].value = None
for x in range(1, row+1):
for y in range(1, col+1):
# 使用cell[x][y] = cell[y][x]的思路,将data中的值,录入到坐标轴倒置的新cell中
# 但在传递数值时,要注意的格式是dict['Key']=value, 操作的是字典和列表
# 在实际编程中,经常提示对元组进行赋值的error提示
X=get_column_letter(x)
sheet[X+str(y)] = data[str(x),str(y)]
wb.save('inverter.xlsx')
剩下还有两个练习分别是
将text文件中本文录入到excel文件中
将excel文件的单元格读取到text文件中
比较简单,暂时不写了,以后闲的时候补上。