讀取 Excel 指定欄,利用列表維持順序去重 (保留首次出現順序),適用於資料清洗、字典建立前處理。
import xlrd
def open_excel(file_name="simple.xls"):
try:
return xlrd.open_workbook(file_name)
except Exception as e:
print(str(e))
return None
def scan_excel(sheet_name='Sheet1'):
wb = open_excel()
return wb.sheet_by_name(sheet_name) if wb else None
def unique_col(col_index=0):
sh = scan_excel()
if not sh: return
col_vals = sh.col_values(col_index)
seen = []
for v in col_vals:
if v not in seen:
seen.append(v)
print("Original:", col_vals)
print("Unique: ", seen)
if __name__ == '__main__':
unique_col()
Original: [1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0, 4.0] Unique: [1.0, 2.0, 3.0, 4.0]
def unique_col_fast(col_index=0):
sh = scan_excel()
if not sh: return
col_vals = sh.col_values(col_index)
# Python 3.7+ dict 保證插入順序
unique = list(dict.fromkeys(col_vals))
print("Unique:", unique)
時間複雜度從 O(n²) 降為 O(n),大欄位明顯加速。
import openpyxl
wb = openpyxl.Workbook()
ws = wb.active
for i, val in enumerate(unique, 1):
ws.cell(row=i, column=1, value=val)
wb.save('unique_output.xlsx')
openpyxl.load_workbook。int 或保留字串。