用python如何繪制表格不同顏色的excel
發(fā)布日期:2021-12-14 07:26 | 文章來(lái)源:站長(zhǎng)之家
需求:

需求簡(jiǎn)單:但是感覺(jué)最后那部分遍歷有意思:S型數(shù)組賦值,考慮到下標(biāo),簡(jiǎn)單題
先實(shí)現(xiàn)個(gè)差不多的
m = 5 cols = 9 rows = 4 nums = [0, 1] array = [[-1 for _ in range(9)] for _ in range(4)] i, j = 0, 0 t = 0 index = -1 while t < cols * rows: if i % rows == 0 and i > 0: j += 1 i -= 1 if i < 0: j += 1 i += 1 # if t % m == 0: # index = (index + 1) % len(nums) array[i][j] = t # index if j % 2 == 0: # 0,2,..2n 下 i += 1 else: # 1,3, 2n+1 上 i -= 1 t += 1 for i in range(4): print(array[i])

需求代碼:
from openpyxl import Workbook
from openpyxl.styles import PatternFill, Side, Border
# 仿照excel格式
# excel文件路徑
file_path = 'C:/Users/Lenovo/Desktop/工作簿2.xlsx'
colors = ['000000', '44546A', 'CC00FF', '00008B']
colorsLen = len(colors)
fills = [PatternFill("solid", fgColor=color) for color in colors]
workbook = Workbook()
sheet = workbook.create_sheet("Sheet1", 0)
rows, cols = 19, 9
colorIndex = -1
block_height = 5
# 按行
for i in range(int(rows / block_height)):
for j in range(cols):
colorIndex = (colorIndex + 1) % colorsLen
for p in range(block_height):
row = block_height * i + p
col = j
cell = sheet.cell(column=col + 1, row=row + 1)
cell.fill = fills[colorIndex]
cell.border = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
# 按列
if rows % block_height != 0:
newRows = rows % block_height
preRows = rows - rows % newRows - 1
newCols = cols
i, j = 0, 0
t = 0
while t < newCols * newRows:
if i % newRows == 0 and i > 0:
j += 1
i -= 1
if i < 0:
j += 1
i += 1
if t % block_height == 0:
colorIndex = (colorIndex + 1) % colorsLen
cell = sheet.cell(column=j + 1, row=preRows + i + 1)
cell.fill = fills[colorIndex]
cell.border = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
if j % 2 == 0: # 0,2,..2n 下
i += 1
else: # 1,3, 2n+1 上
i -= 1
t += 1
workbook.save(file_path)
# 下面是學(xué)習(xí)讀取的部分代碼
# wb = openpyxl.load_workbook(file_path)
# sheet_name = 'Sheet1'
# sheet = wb.get_sheet_by_name(sheet_name)
# for r in range(1, sheet.max_row + 1):
# for c in range(1, sheet.max_column + 1):
#item = sheet.cell(row=r, column=c)
#print(item, end=' ')
# print()
# wb.save(file_path)

顏色沒(méi)對(duì)上,意思差不多就行了
總結(jié)
到此這篇關(guān)于用python如何繪制表格不同顏色excel的文章就介紹到這了,更多相關(guān)python繪制不同顏色excel內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
相關(guān)文章
關(guān)注官方微信