autosar arxml文件导出接口信息并转为Excel格式存储
import pandas as pd
from lxml import etree
from pathlib import Path
from openpyxl.utils import get_column_letter
def parse_arxml(arxml_file):
"""
解析 ARXML 文件,提取 Port 和所属模块信息
"""
tree = etree.parse(arxml_file)
root = tree.getroot()
ns = {
'ns': 'http://autosar.org/schema/r4.0',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance'
}
ports_data = []
for component in root.findall('.//ns:SW-COMPONENT-TYPE', ns):
component_name = component.find('ns:SHORT-NAME', ns).text
for p_port in component.findall('.//ns:P-PORT-PROTOTYPE', ns):
port_name = p_port.find('ns:SHORT-NAME', ns).text
ports_data.append({
'Module': component_name,
'Port Name': port_name,
'Port Type': 'P-Port',
'Interface': p_port.find('.//ns:PROVIDED-INTERFACE-TREF', ns).text if p_port.find('.//ns:PROVIDED-INTERFACE-TREF', ns) is not None else 'N/A'
})
for r_port in component.findall('.//ns:R-PORT-PROTOTYPE', ns):
port_name = r_port.find('ns:SHORT-NAME', ns).text
ports_data.append({
'Module': component_name,
'Port Name': port_name,
'Port Type': 'R-Port',
'Interface': r_port.find('.//ns:REQUIRED-INTERFACE-TREF', ns).text if r_port.find('.//ns:REQUIRED-INTERFACE-TREF', ns) is not None else 'N/A'
})
return ports_data
def export_to_excel(data, output_file):
"""
将数据导出到Excel文件
"""
df = pd.DataFrame(data,columns = ['Module', 'Port Name', 'Port Type', 'Interface'])
with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
df.to_excel(writer, index=False, sheet_name='Ports')
workbook = writer.book
worksheet = writer.sheets['Ports']
for col in worksheet.columns:
max_length = max(len(str(cell.value)) for cell in col)
worksheet.column_dimensions[col[0].column].width = max_length + 2
for cell in worksheet[1]:
cell.font = Font(bold=True)
cell.fill = PatternFill(start_color="FFFF00", fill_type="solid")
def main():
arxml_file = input("请输入ARXML文件路径: ").strip('"')
if not Path(arxml_file).exists():
print(f"错误: 文件 {arxml_file} 不存在")
return
print("正在解析ARXML文件...")
try:
ports_data = parse_arxml(arxml_file)
except Exception as e:
print(f"解析ARXML文件时出错: {str(e)}")
return
if not ports_data:
print("警告: 未找到任何Port信息")
return
output_file = Path(arxml_file).with_name(f"{Path(arxml_file).stem}_ports.xlsx")
print(f"正在导出结果到 {output_file}...")
export_to_excel(ports_data, output_file)
print("处理完成!")
if __name__ == "__main__":
from openpyxl.styles import Font, PatternFill
main()