最近碰上一個需求,需要給物流行業的Excel匹配派送費,具體完整需求較為復雜,其中涉及的一個麻煩點可以拿出來給大家講講,
這些物流訂單表中,通過連續相同的顏色標識屬于合票派送,并不像資料庫有單獨的欄位標記,今天我們的實作目標是讀取連續相同的顏色,標記同一個分組編號,
通過openpyxl讀取xlsx格式的顏色比較簡單不作演示了,讀者也可以考慮先將xls格式先轉換為xlsx格式再讀取顏色,不過我今天演示的是使用xlrd庫直接讀取xls格式的Excel表,從而決議出顏色,并分析是否是連續相同的顏色,給一個唯一的分組編號,
舉個例子,對于如下Excel表:

這4個顏色連續相同的的單元格,標記為同一個編號,
首先我們讀取這個Excel表:
import xlrd
# 打開Excel,為了讀取樣式資訊需要指定formatting_info=True
book = xlrd.open_workbook("test.xls", formatting_info=True)
# 獲取第一張sheet
sheet = book.sheets()[0]
sheet
<xlrd.sheet.Sheet at 0x1bb232524c8>
首先我們先嘗試讀取第一個有顏色的單元格:
cell = sheet.cell(2, 1)
print(cell.value, cell.xf_index)
KSTD152 77
已經成功讀取到具體的值和對應的樣式索引,
**那么如果根據索引獲取顏色值呢?**這時需要使用全域顏色定義表:
colour_index = book.xf_list[cell.xf_index].background.pattern_colour_index
book.colour_map[colour_index]
(255, 102, 0)
將以上程序封裝起來,再測驗一下讀取另一個合票的顏色:
def get_cell_color(cell):
colour_index = book.xf_list[cell.xf_index].background.pattern_colour_index
return book.colour_map[colour_index]
get_cell_color(sheet.cell(8, 1))
(204, 204, 255)
那說明我們已經可以提取出指定單元格的顏色值了,
**如何批量讀取資料?**使用get_rows生成器最簡單:
import pandas as pd
rows = sheet.get_rows()
header = [cell.value for cell in next(rows)]
data = []
for row in rows:
data.append([cell.value for cell in row])
df = pd.DataFrame(data, columns=header)
df.head(20)

基于以上代碼,下面我們批量讀取整個Excel的資料,并根據顏色值賦予一個合票編號:
import pandas as pd
rows = sheet.get_rows()
header = [cell.value for cell in next(rows)]
header.append("合票編號")
data = []
last_color = None
num = 0
for row in rows:
t = [cell.value for cell in row]
color = get_cell_color(row[1])
if color and color != (255, 255, 255):
if color != last_color:
num += 1
t.append(num)
else:
t.append(pd.NA)
last_color = color
data.append(t)
df = pd.DataFrame(data, columns=header)
df.head(20)
可以看到已經正確的給連續相同的顏色打上了相同的編號:

這樣我們就解決了這個問題,完整代碼如下:
import pandas as pd
import xlrd
def get_cell_color(cell):
colour_index = book.xf_list[cell.xf_index].background.pattern_colour_index
return book.colour_map[colour_index]
# 打開Excel,為了讀取樣式資訊需要指定formatting_info=True
book = xlrd.open_workbook("test.xls", formatting_info=True)
# 獲取第一張sheet
sheet = book.sheets()[0]
rows = sheet.get_rows()
header = [cell.value for cell in next(rows)]
header.append("合票編號")
data = []
last_color = None
num = 0
for row in rows:
t = [cell.value for cell in row]
color = get_cell_color(row[1])
if color and color != (255, 255, 255):
if color != last_color:
num += 1
t.append(num)
else:
t.append(pd.NA)
last_color = color
data.append(t)
df = pd.DataFrame(data, columns=header)
df
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/296641.html
標籤:其他
上一篇:小白轉行軟體測驗,面試3天接到3個offer,月薪10k(程式人生)
下一篇:希爾排序(Shell Sort)
