假設 excel 中有 ABC三個欄位,請逐行讀取,並且寫入到一個dict 中對應的 list 中

 

 




你可以使用 pandas 來讀取 Excel,然後將每一列的數據存入一個 dict,對應到 list 中。以下是 Python 的程式碼:

 

方法 1:使用 pandas

 

import pandas as pd

# 讀取 Excel 文件
file_path = "your_file.xlsx"  # 請替換為你的檔案名稱
df = pd.read_excel(file_path)

# 初始化 dict
data_dict = {col: [] for col in df.columns}

# 逐行讀取並存入 dict
for _, row in df.iterrows():
    for col in df.columns:
        data_dict[col].append(row[col])

# 輸出結果
print(data_dict)

 

方法 2:使用 openpyxl(不依賴 pandas)

 

from openpyxl import load_workbook

# 讀取 Excel
file_path = "your_file.xlsx"
wb = load_workbook(filename=file_path)
sheet = wb.active

# 初始化 dict
data_dict = {}

# 讀取標題
headers = [cell.value for cell in sheet[1]]
for header in headers:
    data_dict[header] = []

# 逐行讀取數據
for row in sheet.iter_rows(min_row=2, values_only=True):
    for header, value in zip(headers, row):
        data_dict[header].append(value)

# 輸出結果
print(data_dict)

 

兩種方法的比較:
pandas 方法:簡潔且快速,適合處理大數據表。
openpyxl 方法:不依賴 pandas,適合純 Python 環境。
這樣 data_dict 會變成:

 

 

{
    "A": [A1, A2, A3, ...],
    "B": [B1, B2, B3, ...],
    "C": [C1, C2, C3, ...]
}