1. 處理Excel 電子表格筆記(第12章)
本文主要介紹openpyxl 的2.5.12版處理excel電子表格,原書是2.1.4 版,OpenPyXL 團隊會經常發佈新版本。不過不用擔心,新版本應該在相當長的時間內向後兼容。如果你有新版本,想看看它提供了什麼新功能,可以查看OpenPyXL 的完整文檔:
http://openpyxl.readthedocs.org/。
1.1 讀取Excel文檔
常用函數如下:
函數(2.5.12) | 函數(2.1.4) | 用途 | 備註 |
---|---|---|---|
openpyxl.load_workbook(‘example.xlsx’) | openpyxl.load_workbook(‘example.xlsx’) | 打開excel文檔 | |
wb.sheetnames | wb.get_sheet_names() | 取得工作簿中所有表名的列表 | |
sheet = wb[‘Sheet’] | sheet = wb.get_sheet_by_name(‘Sheet’) | 獲得工作簿表格Sheet | |
sheet.title | sheet.title | 獲得sheet的表格名 | |
anotherSheet = wb.active | anotherSheet = wb.get_active_sheet() | 獲得當前活動表 | 活動表就是工作簿在Excel 中打開時出現的工作表 |
sheet[‘A1’].value | sheet[‘A1’].value | 獲得A1框格的值 | 可以通過=賦值改變A1框格的值 |
sheet.cell(row=1, column=2) | sheet.cell(row=1, column=2) | 獲得B2框格的值 | 另一種賦值方法,row表示行號,row代表用數字標識的列號 |
sheet.max_row/sheet.max_column | sheet.get_highest_row()/sheet.get_highest_column() | 獲得表格最大行數/列數 | 返回整數 |
from openpyxl.utils import get_column_letter, column_index_from_string | from openpyxl.cell import get_column_letter, column_index_from_string | 調用數字字母轉換函數 | |
get_column_letter(2) | get_column_letter(2) | 將數字2轉爲字母B | |
column_index_from_string(‘AA’) | column_index_from_string(‘AA’) | 將字母AA轉爲數字27 | |
tuple(sheet[‘A1’:‘C3’]) | tuple(sheet[‘A1’:‘C3’]) | 獲得A1到C3處的單元格 |
1.2 寫入Excel文檔
常用函數如下:
函數(2.5.12) | 函數(2.1.4) | 用途 | 備註 |
---|---|---|---|
wb = openpyxl.Workbook() | wb = openpyxl.Workbook() | 創建新的工作表對象 | |
wb.create_sheet(index=2, title=‘Middle Sheet’)) | wb.create_sheet(index=2, title=‘Middle Sheet’)) | 創建序號爲index+1的新工作表 | 可以缺省輸入參數 |
wb.remove(wb[‘Sheet1’]) | wb.remove_sheet(wb.get_sheet_by_name(‘Sheet’)) | 刪除工作表Sheet1 | |
wb.save(‘example_copy.xlsx’) | wb.save(‘example_copy.xlsx’) | 保存xlsx文件 |
1.3 表格設置
常用函數如下:
函數(2.5.12) | 函數(2.1.4) | 用途 | 備註 |
---|---|---|---|
from openpyxl.styles import Font | from openpyxl.styles import Font, Style | 導入字體設置模塊 | |
italic24Font = Font(name=‘Times New Roman’,size=24, italic=True,bold=True) sheet[‘A1’].font = italic24Font |
italic24Font = Font(name=‘Times New Roman’,size=24, italic=True,bold=True) styleObj = Style(font=italic24Font) sheet[‘A1’].style=styleObj |
設置A1單元格字體,斜體加粗,字號24 | |
sheet[‘A3’] = ‘=SUM(A1:A2)’ | sheet[‘A3’] = ‘=SUM(A1:A2)’ | 設置公式 | 類似excel公式處理 |
sheet.row_dimensions[1].height = 70 | sheet.row_dimensions[1].height = 70 | 設置第1行高度 | |
sheet.column_dimensions[‘B’].width = 20 | sheet.column_dimensions[‘B’].width = 20 | 設置第B列寬度 | |
sheet.merge_cells(‘A1:D3’) | sheet.merge_cells(‘A1:D3’) | 將’A1:D3’12 個單元格合併爲一個單元格 | |
sheet.unmerge_cells(‘C5:D5’) | sheet.unmerge_cells(‘C5:D5’) | 解除單元格合併 |
2. 項目練習
2.1 從電子表格中讀取數據
2010 年美國人口普查數據censuspopdata.xlsx,可以從https://download.csdn.net/download/luohenyj/11266976 下載。程序主要功能:
- 讀取電子表格數據
- 填充數據結構
- 將結果寫入文件
代碼如下:
import openpyxl
import pprint
print('Opening workbook...')
# 打開excel文檔
wb = openpyxl.load_workbook('censuspopdata.xlsx')
# 打開 工作表
#sheet = wb.get_sheet_by_name('Population by Census Tract')
sheet = wb['Population by Census Tract']
countyData = {}
print('Reading rows...')
# 按行讀取數據
for row in range(2, sheet.max_row + 1):
state = sheet['B' + str(row)].value
county = sheet['C' + str(row)].value
pop = sheet['D' + str(row)].value
# Make sure the key for this state exists.
countyData.setdefault(state, {})
# country沒有時設置的默認值
countyData[state].setdefault(county, {'tracts': 0, 'pop': 0})
# Each row represents one census tract, so increment by one.
# 計算每個縣中普查區的數
countyData[state][county]['tracts'] += 1
# Increase the county pop by the pop in this census tract.
# 統計總人口
countyData[state][county]['pop'] += int(pop)
# Open a new text file and write the contents of countyData to it.
print('Writing results...')
resultFile = open('census2010.py', 'w')
# 保存數據
resultFile.write('allData = ' + pprint.pformat(countyData))
resultFile.close()
print('Done.')
'''
import os
# 導入py數據文件
import census2010
# 打印某一項數據
census2010.allData['AK']['Anchorage']
anchoragePop = census2010.allData['AK']['Anchorage']['pop']
print('The 2010 population of Anchorage was ' + str(anchoragePop))
'''
2.2 更新一個電子表格
從produceSales.xlsx找到特定類型的產品,並更新它們的價格。produceSales.xlsx可以從https://download.csdn.net/download/luohenyj/11266976 下載
import openpyxl
# 打開文檔
wb = openpyxl.load_workbook('produceSales.xlsx')
#sheet = wb.get_sheet_by_name('Sheet')
sheet = wb['Sheet']
# 要改變的價格
PRICE_UPDATES = {'Garlic': 3.07,
'Celery': 1.19,
'Lemon': 1.27}
# skip the first row 跳過首行
for rowNum in range(2, sheet.max_row):
# 獲得該行第一列的值
produceName = sheet.cell(row=rowNum, column=1).value
# 判斷鍵值
if produceName in PRICE_UPDATES:
# 更新值
sheet.cell(row=rowNum, column=2).value = PRICE_UPDATES[produceName]
wb.save('updatedProduceSales.xlsx')
2.3 乘法表
從命令行接受數字N,在一個Excel 電子表格中創建一個N×N 的乘法表。
import openpyxl
from openpyxl.utils import get_column_letter, column_index_from_string
# 設置字體風格
from openpyxl.styles import Font
wb = openpyxl.Workbook()
sheet = wb['Sheet']
print("Please input N:")
N = int(input())
A = get_column_letter(1)
# 設置字體加粗
fontObj = Font(bold=True)
# 設置行
for row in range(2, N+2):
sheet['A'+str(row)] = row-1
sheet['A'+str(row)].font = fontObj
# 設置列
for col in range(2, N+2):
colName = get_column_letter(col)
sheet[colName+str(1)] = col-1
sheet[colName+str(1)].font = fontObj
for row in range(2, N+2):
for col in range(2, N+2):
colName = get_column_letter(col)
rowName = row
sheet[colName+str(row)] = sheet[colName+str(1)
].value*sheet['A'+str(row)].value
wb.save('multiplicationTable.xlsx')
wb.close()
Please input N:
9
2.4 空行插入程序
命令行參數輸入N和M。從第N行開始,在電子表格中插入M 個空行
import openpyxl
xlsxPath='multiplicationTable.xlsx'
# 打開文件
wb = openpyxl.load_workbook(xlsxPath)
sheet = wb['Sheet']
print("空行起始行號:")
rowBlank=int(input())
print("空行數:")
rowBlanInsert=int(input())
# 新的文件
wb_save = openpyxl.Workbook()
sheet_save = wb_save['Sheet']
# 保存空行的數據
for row in range(1,sheet.max_row+1):
for col in range(1,sheet.max_column+1):
# 保存前rowBlank的值
if row<rowBlank:
sheet_save.cell(row,col).value=sheet.cell(row,col).value
else:
sheet_save.cell(row+rowBlanInsert,col).value=sheet.cell(row,col).value
wb_save.save('blankRowInserter.xlsx')
空行起始行號:
2
空行數:
3
2.5 電子表格單元格翻轉程序
編寫一個程序,翻轉電子表格中行和列的單元格
import openpyxl
xlsxPath = 'blankRowInserter.xlsx'
# 打開文件
wb = openpyxl.load_workbook(xlsxPath)
sheet = wb['Sheet']
# 新的文件
wb_save = openpyxl.Workbook()
sheet_save = wb_save['Sheet']
# 翻轉數據
for row in range(1, sheet.max_row+1):
for col in range(1, sheet.max_column+1):
sheet_save.cell(col, row).value = sheet.cell(row, col).value
wb_save.save('transSheet.xlsx')
2.6 文本文件到電子表格
讀入幾個文本文件的內容(可以自己創造這些文本文件),並將這些內容插入一個電子表格,每行寫入一行文本。第一個文本文件中的行將寫入
列A 中的單元格,第二個文本文件中的行將寫入列B 中的單元格,以此類推。
import openpyxl
import os
wb = openpyxl.Workbook()
sheet = wb['Sheet']
searchPath = './my_test'
# 返回指定目錄下所有的文件名和文件夾名列表
fileNames = os.listdir(searchPath)
txtNames = []
for fileName in fileNames:
# 如果結尾是txt
if fileName.endswith('.txt'):
# 保存到列表
txtNames.append(fileName)
# 遍歷文件
for i in range(len(txtNames)):
txtPath = os.path.join(searchPath, txtNames[i])
file = open(txtPath)
fileContents = file.readlines()
for j in range(len(fileContents)):
sheet.cell(i+1, j+1).value = fileContents[j]
wb.save('txtToXlsx.xlsx')
2.7 電子表格到文本文件
將列A 中的單元格寫入一個文本文件,將列B 中的單元格寫入另一個文本文件,以此類推。
# -*- coding: utf-8 -*-
import openpyxl
import os
wb = openpyxl.load_workbook('txtToXlsx.xlsx')
sheet = wb.active
for rows in range(sheet.max_row):
txtFile = open('%s.txt' % (rows), 'w')
# 遍歷行
for cols in sheet[rows+1]:
txtFile.write(str(cols.value))
txtFile.close()