py multiplicationTable.py 6
它应该创建一个图12-11所示的电子表格。
import sys, openpyxl
from openpyxl.styles import Font
Num = int(sys.argv[1])
wb = openpyxl.Workbook()
sheet = wb['Sheet']
#加粗字体
boldFont = Font(bold=True)
#字体+数值
for i in range(1, Num+1):
sheet.cell(row = i+1, column = 1).font = boldFont
sheet.cell(row = i+1, column = 1).value = i
#字体+数值
for j in range(1, Num+1):
sheet.cell(row = 1, column = j+1).font = boldFont
sheet.cell(row = 1, column = j+1).value = j
#目标单元格值 = 最左单元格值 * 最上单元格值
for i in range(2, Num+2):
for j in range(2, Num+2):
sheet.cell(row = i, column = j).value = \
sheet.cell(row = i, column = 1).value * \
sheet.cell(row = 1, column = j).value
wb.save('12311.xlsx')
python blankRowInserter.py 3 2 myProduce .xIsx
import sys, openpyxl
from openpyxl.utils import get_column_letter
#获取行号以及行数
lineRow, numRow = int(sys.argv[1]), int(sys.argv[2])
#打开源工作表,得到最大行、列
wbSour = openpyxl.load_workbook(sys.argv[3])
sheetSour = wbSour['Sheet']
maxRowSour,maxColumnSour = sheetSour.max_row, sheetSour.max_column
#打开目标工作表,使用get_column_letter得到要合并范围
wbAim = openpyxl.Workbook()
sheetAim = wbAim['Sheet']
numFirst = get_column_letter(1) + str(lineRow)
numLast = get_column_letter(maxColumnSour) + str(lineRow+numRow-1)
#行号前照抄,行号+行数来跳行
for i in range(1, maxRowSour + 1):
for j in range(1, maxColumnSour + 1):
if i < lineRow:
sheetAim.cell(row=i, column=j).value = sheetSour.cell(row=i, column=j).value
else:
sheetAim.cell(row=i+numRow, column=j).value = sheetSour.cell(row=i, column=j).value
#将numFirst:+numLast的范围合并
sheetAim.merge_cells(''+numFirst+':'+numLast+'')
wbAim.save('text12311.xlsx')
import openpyxl
wbSour = openpyxl.load_workbook('text12311.xlsx')
sheetSour = wbSour['Sheet']
maxColumn = sheetSour.max_column
wbAim = openpyxl.Workbook()
sheetAim = wbAim['Sheet']
#计算核心
for i in range(maxColumn):
#定位坐标,因为j不是int型数据
n = 1
#利用整列读取,获得一列的数值
for j in list(sheetSour.columns)[i]:
#将x,y坐标替换成y,x坐标位
sheetAim.cell(row=i+1, column=n).value = j.value
n += 1
wbAim.save('text212311.xlsx')
import openpyxl
#嫌麻烦就没写遍历整个文件夹来获取txt文件名
#嫌麻烦就没写正则表达式筛选txt文件
listTxt = [open(r'.\121341.txt'), open(r'.\121342.txt')]
wb = openpyxl.Workbook()
sheet = wb['Sheet']
#已知有两个txt
for i in range(2):
#获得当前文本有多少行
readLineTxt = listTxt[i].readlines()
#将行写入excel表格中
for j in range(len(readLineTxt)):
sheet.cell(row=j+1, column=i+1).value = readLineTxt[j]
listTxt[i].close()
wb.save('text12134.xlsx')
import openpyxl
wb = openpyxl.load_workbook('text12134.xlsx')
sheet = wb['Sheet']
maxColumn = sheet.max_column
for i in range(maxColumn):
txtFile = open('.\\'+ str(i+1) +'.txt', 'w')
#利用整列读取,获得一列的数值
for j in list(sheet.columns)[i]:
txtFile.write(str(j.value))
txtFile.close()
新版的openpyxl有很多函数重写了,在这列出书上和新版的差异:
使用openpyxl来处理excel表格时,要注意: