本帖最後由 s20012797 於 2024-7-5 13:02 編輯
VBA- Sub FormatData()
- Dim lastRow As Long
- Dim i As Long
-
- ' 找到最後一行數據
- lastRow = Cells(Rows.Count, "A").End(xlUp).Row
-
- ' 遍歷每一行數據
- For i = 1 To lastRow
- ' 提取產品 ID 的前 6 位數字,並補零到 6 位
- Cells(i, "B").Formula = "=LEFT(TEXT(LEFT(A" & i & ",MIN(IF(ISNUMBER(--MID(A" & i & ",ROW(INDIRECT(""1:6"")),1)),999,ROW(INDIRECT(""1:6"")))})-1),""000000"")&MID(A" & i & ",MIN(IF(ISNUMBER(--MID(A" & i & ",ROW(INDIRECT(""1:6"")),1)),999,ROW(INDIRECT(""1:6"")})),LEN(A" & i & ")),LEN(A" & i & ")-MIN(IF(ISNUMBER(--MID(A" & i & ",ROW(INDIRECT(""1:6"")),1)),999,ROW(INDIRECT(""1:6"")})))+1)&REPT("" "", 30-LEN(Cells(i,""B"").Formula))"
- ' 將結果填入 B 列
- Cells(i, "B").Value = Cells(i, "B").Formula
- Next i
-
- ' 調整列寬
- Range("A:B").EntireColumn.AutoFit
- End Sub
複製代碼 Python- import re
- # 讀取資料
- data = []with open('input_file.txt', 'r') as file:
- for line in file:
- data.append(line.strip())
- # 格式化數據
- for i, row in enumerate(data):
- # 提取產品 ID 的前 6 位數字,並補零到 6 位
- product_id = row[:6].zfill(6) + row[6:]
- data[i] = product_id.ljust(30)
- # 寫入輸出檔案
- with open('output_file.txt', 'w') as file:
- file.writelines([line + '\n' for line in data])
- # 調整列寬
- print("資料已成功格式化,列寬已自動調整。")
複製代碼 |