Excel是微軟出品的辦公神器,大部分讀者相信或多或少都用過,其自帶的函式豐富,可以進行復雜的資料運算、分析以及可視化的輸出,到目前為止沒有出現可以望其項背的競品,大部分競品不是在模仿的路上,就是在失敗的路上,
雖然Excel不是資料庫管理系統,Excel檔案也不是完全結構化的檔案,但它以行列形式保存了大量的資料,也可以將其視作準資料庫檔案,歷史上,python有許多庫能夠操作Excel,例如lsxwriter、openpyxl、pandas、xlwings等,只是功能多少的問題,我們使用openpyxl庫來操作excel檔案,需要說明的是,由于Excel多次重大升級后,早期版本與現代版本差距明顯,openpyxl只能夠打開后綴為xlsx的檔案,
它的安裝程序如下:
pip install openpyxl
使用前文介紹的faker庫,創建一些模擬資料,用于后續的讀寫操作,代碼示例如下:
import random from faker import Faker from openpyxl import Workbook # 最高薪資(單位為K) maxsalary = 30 def fakedata(maxtimes): # 模擬資料,人名+薪資 fake = Faker('zh_CN') data_total = [[fake.name(), random.randint(0, maxsalary)] for x in range(maxtimes)] return data_total def create_xlsx(filename): fakesalary = fakedata(100) wb = Workbook() # 獲取被激活的 worksheet ws = wb.active for info in fakesalary: ws.append(info) wb.save(filename) create_xlsx("d:/salary.xlsx")
Excel檔案創建后效果如下圖所示:

除此之外,可以打開已經有的Excel檔案,對表格、單元、行、列進行操作,相關示例代碼如下:
import random from faker import Faker from openpyxl import load_workbook def show_sheets(filename): wb = load_workbook(filename) return wb.sheetnames def create_sheet(filename, name, title): wb = load_workbook(filename) ws1 = wb.create_sheet(name) ws1.title = title ws1["A1"]=8848.8848 ws1["B2"]="hello raindrop" wb.save(filename) def ops_data(filename,sheetname): wb = load_workbook(filename) ws1 = wb.get_sheet_by_name(u"Sheet") # 操作單列 for cell in ws1["A"]: print(cell.value) # 操作單行 for cell in ws1["1"]: print(cell.value) # 操作多列 for column in ws1['A:B']: for cell in column: print(cell.value) # 操作多行 for row in ws1['1:3']: for cell in row: print(cell.value) # 所有行 for row in ws1.iter_rows(): for cell in row: print(cell.value) # 所有列 for column in ws1.iter_cols(): for cell in column: print(cell.value) excelname = 'd:/salary.xlsx' print(show_sheets(excelname)) create_sheet(excelname, "demosheet", "hello excel") ops_data(excelname, "sheet")
當能夠隨意操作Excel檔案時,就完成了資料分析最基礎的作業之一,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/547458.html
標籤:Python
