《Python编程快速上手—让繁琐工作自动化》第12章实践项目2020-02-16

12.13.1 乘法表

法一

from openpyxl.workbook import Workbook
from openpyxl.styles import Font
import sys
import os

os.chdir('.')  #记得改变当前工作目录至目的地不然找不到文件
n = int(sys.argv[1])
wb = Workbook()
ws = wb.active
ws.freeze_panes = 'B2'  #冻结窗口
f = Font(bold=True)

#将第一行和第一列数字填入并设置格式
for i in range(1,n+1):    
    ws.cell(row=1,column=i+1).value = i
    ws.cell(row=i+1,column=1).value = i
    ws.cell(row=1,column=i+1).font = f
    ws.cell(row=i+1,column=1).font = f

#遍历剩下单元格将选取对应的数字相乘得到的结果填入
for row in ws.iter_rows(min_row=2, min_col=2, max_row=n+1,max_col=n+1):
    for cell in row:
        cell.value = int(ws.cell(row=1,column=cell.column).value)\
                   *int(ws['A'+str(cell.row)].value)
    

wb.save('121301.xlsx')
print('DONE')

法二

from openpyxl.workbook import Workbook
from openpyxl.styles import Font
import sys

wb = Workbook()
ws = wb.active
ws.freeze_panes = 'B2'

n = int(sys.argv[1])
f = Font(bold=True)

#判断分支对应填入
for row in ws.iter_rows(min_row=1,min_col=1,max_row=n+1,max_col=n+1):
    for c in row:
        row = c.row
        col = c.column
        if row == 1 and col == 1:
            continue
        elif row == 1:
            c.value = col - 1
            c.font = f
        elif col == 1:
            c.value = row - 1
            c.font = f
        else:
            c.value = (row-1)*(col-1)


wb.save('12130102.xlsx')
print('DONE')
        

总结:法二相对较简洁些,法一的思路个人认为比较常规。

12.13.02

from openpyxl import load_workbook
import sys
import os

os.chdir(r'C:\Users\Yuuunoooo\Desktop')
n = int(sys.argv[1])
m = int(sys.argv[2])

wb = load_workbook('sampleChart.xlsx')
ws = wb['Sheet']

for i in range(m):
    ws.insert_rows(n)
    
wb.save('sampleChart2.0.xlsx')
print('DONE')

总结:没有用书上的一些提示。因为查官方字典发现有了Sheet对象的insert_rows(n)直接在第n行插入,于是一切变得不一样。PS:在保存时保存为新的文件这样就可以保留原文件了。

12.13.03 电子表格单元格翻转

法1

from openpyxl import load_workbook
from openpyxl import Workbook

wb = load_workbook('123.xlsx')
ws = wb['Sheet1']

cellList = []
rowList = []

for col in range(1,ws.max_column + 1):
    for row in range(1,ws.max_row + 1):
        rowList.append(ws.cell(column=col,row=row).value) #将一列数据写入列表rowList
    cellList.append(rowList) #将rowList添加到cellList列表
    rowList = []    #更新rowList

ws2 = wb.create_sheet('Sheet')

#将数据写入新列表
for x in range(len(cellList)):
    for y in range(len(cellList[0])):
        ws2.cell(column=y+1,row=x+1).value = cellList[x][y]

wb.remove(ws)
wb.save('new_123.xlsx')
print('DONE')

法2

from openpyxl import load_workbook

wb = load_workbook('123.xlsx')
ws = wb['Sheet1']

cellList = []

maxRow = ws.max_row
maxCol = ws.max_column 
for col in ws.iter_cols(min_row=1, max_row=maxRow, max_col=maxCol):
    for cell in col:
        cellList.append(cell.value)
        

ws2 = wb.create_sheet('newSheet1')

n = 0
for row in ws2.iter_rows(min_row=1, max_row=maxCol, max_col=maxRow):
    for cell in row:
        cell.value = cellList[n]
        n += 1
        #print(cell.value) 

        
wb.remove(ws)
wb.save('new_123.xlsx')
print('DONE')

思路:1.法一是按照书上的提示思路写的,将电子表格中的数据读入一个列表的列表
2.用创建新的Sheet方法写入新数据,这样就不用删除掉原数据再写了。(主要是没找到什么好的方法去删除整个Sheet的数据= =用循环还不如直接创建一个新的)

  1. 法二的思路是在想尝试用字典方法写一遍后发现的。运用了ws.iter_rows()和ws.iter_cols的有序读取方法。发现非常高效就完成了翻转!可以参考官方文档https://openpyxl.readthedocs.io/en/stable/tutorial.html 了解上述两种方法。

12.13.04 文本文件到电子表格

#文本文件到电子表格

from openpyxl.workbook import Workbook

fileList = ['1.txt','2.txt','3.txt']
wb = Workbook()
ws = wb.active

for i in range(len(fileList)):
    file = open(fileList[i], 'r')
    lineList = file.readlines()

    n = 1    
    for line in lineList:
        ws.cell(column=i+1,row=n).value = line
        n += 1

wb.save('123combine.xlsx')
print('DONE')

12.13.05 电子表格到文本文件

#电子表格到文本文件

from openpyxl import load_workbook

wb = load_workbook('123combine.xlsx')
ws = wb.active


for col in range(1,ws.max_column+1):
    file = open(str(col) + '.txt','w')
    print('writing data to %s ...' % (str(col) + '.txt'))
    for row in range(1,ws.max_row+1):
        line = ws.cell(row=row,column=col).value
        if line != None:
            file.write(str(line)+'\n')
        else:
            continue                                        
    file.close()                

s    
print('DONE')
        

注意:write方法不加str后有些数据会写不进去。暂时还不知道什么原因。各位大神如果知道可以教教我www
以上。如果有什么问题欢迎找我一起探讨:)

你可能感兴趣的:(《Python编程快速上手—让繁琐工作自动化》第12章实践项目2020-02-16)