要求使用VBA或者Python解决
数据原始状态
处理后数据状态
看起來像是把列表的資料 用 “二維” 表顯示。
把代碼放在 ”代码块“ 讓大家可以幫忙找出問題。
我用python处理了一下,应该达到你要求的效果了。
处理前的文件截图:
处理后的文件截图:(New Data标签)
from openpyxl import Workbook, load_workbook
from collections import defaultdict
source_path="data.xlsx"
result_path="data_processed.xlsx"
# 加载数据文件
wb = load_workbook(source_path)
sheet = wb.active
# 处理数据
data = defaultdict(dict)
for row in sheet.iter_rows(min_row=1, values_only=True):
work_condition, column_name, value = row
data[work_condition][column_name] = value
# 输出处理结果
new_sheet = wb.create_sheet('New Data')
new_sheet.append(('工况名称', 'A', 'B', 'C'))
for work_condition in data:
values = [work_condition]
for column_name in ('A', 'B', 'C'):
values.append(data[work_condition].get(column_name, ''))
new_sheet.append(tuple(values))
# 保存结果到新文件
wb.save(result_path)
Excel VBA——字典嵌套和多字典实现数据透视列
Sub 透视列()
Dim row As Long
Dim dict As Object
Dim key As String
Dim key1 As String
Dim arr
Dim i As Long
Dim brr
Dim br
Dim dict1
Dim 标题最大使用列号 As Long
Dim col As Long
row = 1
Set dict = CreateObject("Scripting.Dictionary")
Set dict1 = CreateObject("Scripting.Dictionary")
Do While Sheet1.Range("A" & row).Value <> ""
key = Sheet1.Range("A" & row).Value
'Debug.Print key
If Not dict.Exists(key) Then
Set dict(key) = CreateObject("Scripting.Dictionary")
End If
key1 = Sheet1.Range("B" & row).Value
If Not dict(key).Exists(key1) Then
dict(key)(key1) = Sheet1.Range("C" & row).Value
End If
row = row + 1
Loop
'写入新数据
arr = dict.keys()
For i = LBound(arr) To UBound(arr)
Debug.Print arr(i)
Sheet2.Range("A" & i + 2).Value = arr(i)
brr = dict(arr(i)).keys()
For Each br In brr
If Not dict1.Exists(br) Then
'把br写到标题行
标题最大使用列号 = Sheet2.Cells(1, Sheet2.Columns.Count).End(xlToLeft).Column
col = 标题最大使用列号 + 1
Sheet2.Cells(1, col).Value = br
dict1(br) = col
Else
col = dict1(br)
End If
Sheet2.Cells(i + 2, col).Value = dict(arr(i))(br)
Next br
Next i
Set dict = Nothing
Set dict1 = Nothing
End Sub
请先添加表格“Sheet2”,结果会写入到这个表里。