2023-01-16|閱讀時間 ‧ 約 2 分鐘

【Python辦公自動化筆記-Excel篇7】寫入資料及行、列的插入和刪除

我們可以利用工作表的append()方法,在工作表的列尾添加資料列。
data = (
('8-1', '8-2', '8-3', '8-4', '8-5'),
('9-1', '9-2', '9-3', '9-4', '9-5'),
)

# 在工作表列尾添加2列資料
for row in data:
   ws.append(row)
利用迴圈的技巧,我們可以批次賦予區塊內所有儲存格相同的值。
for row in ws['C3:D6']:
   for cell in row:
       cell.value= 168
我們也可以在指定的列(行)之前插入指定數量的空白列(行),從指定的列(行)開始向下(右)刪除指定數量的列(行)。
ws.insert_rows(idx = 3, amount = 2 )  # 在第3列前插入2
ws.insert_cols(idx = 3, amount = 2)   # 在第3行前插入2
ws.delete_rows(idx = 3, amount = 2)   # 從第3列開始向下刪除2
ws.delete_cols(idx = 3, amount = 2)   # 從第3行開始向右刪除2
分享至
成為作者繼續創作的動力吧!
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言