Python的openpyxl使用記錄(包含合併單元格,圖片下載和圖片插入,設置邊框,設置背景顏色)
背景
因為公司最近要求我做一份自動化導出報告,內容有點多,為了省事,我選用了python,後面估計要自建在線辦公系統,這個後續再講
需要的庫
openpyxl 和Pandas
開始
Execl導入
from openpyxl import load_workbook
#此處抓取一個實體的execl數據對象
file_path = "../印刷站2.xlsx"
workbook = load_workbook(file_path)
單元格設置值
這個很簡單,為了提供複用性,我建了一個工具類具體方法如下
def set_cell_value(workbook, sheet_index, cell, value):"""?置 Excel 文件中指定?元格的值。"""# 加? Excel 文件# ??工作表sheet = workbook.worksheets[sheet_index]# ?置?元格的值sheet[cell] = value
import config
#傳遞數據對象 sheet的索引 單元格 數據
config.set_cell_value(work_book, 1, "D5", data.iloc[0, 0])
單元格設置插入圖片
因為部分資源我使用http地址或者實體ip地址抓取,實際邏輯如下:
工具類
import requests
#下載圖片
def download_image(url):response = requests.get(url)response.raise_for_status() # 确保?求成功return io.BytesIO(response.content)
#插入圖片
def insert_image_to_excel( wb,image_stream, sheet_index, cell,width,heigth):# 加??有的Excel工作簿# ?取指定的工作表(sheet_index?0?始)ws = wb.worksheets[sheet_index]# ?整?片大小? 100x100 像素resized_image_stream = resize_image(image_stream, width, heigth)# 插入?整后的?片到Excelopenpyxl_img = OpenPyxlImage(resized_image_stream)ws.add_image(openpyxl_img, cell)
# Excel數據對象 數據流 sheet所在索引 單元格 長和寬
config.insert_image_to_excel(work_booK, image_stream, 5, col, 200, 200)
合併單元格並設置邊框顏色
這裡我先設置合併的表格的第一行第一列的單元格自顏色,當合併單元格之後自然自己會將邊框顏色設置為整個合併的範圍
from openpyxl.styles import Border, Side
def create_shell_color(shell_info):thin_border = Border(left=Side(style='thin'),right=Side(style='thin'),top=Side(style='thin'),bottom=Side(style='thin'))shell_info.border=thin_border
sheet= work_booK["5.Setup output data"]begin_str = "d" + str(j) + ":h" + str(Y)config.create_shell_color(sheet["D" + str(j)])stage=68sheet.merge_cells(begin_str)
這裡送個好用的函數
輸入數字返回字母
def column_number_to_letter(column_number):"""?列????列字母"""letter = ""while column_number > 0:column_number -= 1letter = chr(column_number % 26 + ord('A')) + lettercolumn_number //= 26return letter