python 操作 Excel 之寫入


假如wb是工作簿(workbook)對象,ws是表單(worksheet)對象:

  1、通過對wb.title賦值可以改變表單名稱
  2、wb.create_sheet(index=表單排位,title='表單名') 添加或插入一張表單
        wb.remove_sheet(wb.get_sheet_by_name('表單名') 刪除表單
  3、wb.get_sheet_names() 能得到所有表單名
  4、ws['B3'] = '你想填啥就填啥‘,更可以雙層循環對單元格進行賦值(數據可以從外部文件獲取)
  5、ws.append(整串數據,可以是列表,也可以是range()產生的序列)

 

創建並保存 Excel 文檔 

調用 openpyxl.Workbook()函數,創建一個新的空 Workbook 對象。

工作簿將從一個工作表開始,名為 Sheet。你可以將新的字符串保存在它的 title 屬性中,從而改變工作表的名字。 當修改Workbook對象或它的工作表和單元格時,電子表格文件不會保存,除非你調 用 save()工作簿方法

import openpyxl
from openpyxl.utils import get_column_letter

wb = openpyxl.Workbook()
sheet = wb.active

# # change the name of the sheet
print(sheet.title)
sheet.title = 'Happy2017'

  

創建和刪除工作表 

利用 create_sheet() 和 remove_sheet()方法,可以在工作簿中添加或刪除工作表。 

create_sheet()方法返回一個新的 Worksheet 對象,名為 SheetX,它默認是工作 簿的最后一個工作表。或者,可以利用 index 和 title 關鍵字參數,指定新工作表的 索引或名稱。 繼續前面的例子,輸入以下代碼:

import openpyxl
from openpyxl.utils import get_column_letter

wb = openpyxl.Workbook()
sheet = wb.active

wb.create_sheet(index=0, title='First Sheet')
wb.create_sheet(index=1, title='Middle Sheet')
print(wb.get_sheet_names()) # 獲取當前工作薄的名字

wb.remove_sheet(wb.get_sheet_by_name('Middle Sheet'))
print(wb.get_sheet_names())

wb.save('temp1.xlsx')

  

將值寫入單元格 

將值寫入單元格,很像將值寫入字典中的鍵。

>>> import openpyxl
>>> wb = openpyxl.Workbook()
>>> sheet = wb['Sheet']
>>> sheet['A1'] = 'Hello world!'
>>> sheet['A1'].value
'Hello world!'

 

批量的進行寫入

import openpyxl
from openpyxl.utils import get_column_letter

wb = openpyxl.Workbook()
sheet = wb.active


ws1 = wb.create_sheet('range names')

# 生成一個0到17個數寫入(1-39行)  
for row in range(1, 40):
    ws1.append(range(17))

ws2 = wb.create_sheet('List')

#  從數組中寫入
rows = [
    ['Number', 'Batch 1', 'Batch2'],
    [2, 40, 30],
    [3, 40, 25],
    [4, 50, 30],
    [5, 30, 10],
    [6, 40, 30],
    [7, 78, 52],
]
for row in rows:
    ws2.append(row)


ws3 = wb.create_sheet(title='Data')
#  指定行和列進行寫入
for row in range(5, 30):
    for col in range(15, 54):
        ws3.cell(column=col, row=row, value=get_column_letter(col))
print(ws3['AA10'].value)

wb.save(filename='empty_book.xlsx')

 

  

小案例: 修改excel中指定的一部分數據

import openpyxl

# The product types and their updated prices
PRICE_UPDATE = {
	'Garlic': 3.17,
    'Celery':1.19,
    'Lemon': 1.27
}

wb = openpyxl.load_workbook('produceSales.xlsx')
ws = wb.get_sheet_by_name('Sheet')

# loop through the rows and update the prices, skip the first row
for rowNum in range(2, ws.max_row+1):

	productName = ws.cell(row=rowNum, column=1).value

	if productName in PRICE_UPDATE:
		ws.cell(row=rowNum, column=2).value = PRICE_UPDATE[productName]

wb.save('updateProduceSales.xlsx')

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM