[python]用python获取DBC文件并保存到EXCEL

[python]用python获取DBC文件并保存到EXCEL_第1张图片

目录

  • 关键词
  • 平台说明
  • 背景
  • 所需库
  • 实现过程
    • 方法1.
    • 1.安装相关库
    • 2.代码实现
    • 方法2
    • 1.安装相关库
    • 2.代码实现

关键词

==python、excel、DBC、openpyxl ==

平台说明

项目 Value
python版本 3.6

背景

在搭建自动化测试平台的时候经常会提取DBC文件中的信息并保存为excel或者其他文件格式,用于自动化测试。本文介绍了如何用python3.6实现获取DBC文件并保存到EXCEL。

所需库

1.python-can:需要它库来解析 DBC 文件,它提供了对 Controller Area Network (CAN) 数据的解析功能,包括 DBC 文件的支持。
2.openpyxl :是一个用于读写 Excel 文件的 Python 库。

实现过程

方法1.

1.安装相关库

pip install openpyxl python-can

2.代码实现

import can
from openpyxl import Workbook

def read_dbc(file_path):
    """
    Read DBC file and return a dictionary with messages and signals.
    """
    db = can.io.db.DB(file_path)
    messages = {}

    for message in db.messages:
        signals = {}
        for signal in message.signals:
            signals[signal.name] = signal

        messages[message.name] = signals

    return messages

def export_to_excel(messages, output_file):
    """
    Export DBC data to Excel file.
    """
    wb = Workbook()
    ws = wb.active

    for message_name, signals in messages.items():
        ws.append([f"Message: {message_name}"])
        ws.append(["Signal Name", "Start Bit", "Length", "Scale", "Offset", "Unit"])

        for signal_name, signal in signals.items():
            ws.append([signal_name, signal.start, signal.length, signal.scale, signal.offset, signal.unit])

        ws.append([])  # Add an empty row between messages

    wb.save(output_file)

if __name__ == "__main__":
    dbc_file_path = "path/to/your/file.dbc"
    excel_output_file = "output.xlsx"

    messages = read_dbc(dbc_file_path)
    export_to_excel(messages, excel_output_file)

方法2

1.安装相关库

pip install cantools openpyxl

2.代码实现


import cantools
from openpyxl import Workbook

def read_dbc_and_save_to_excel(dbc_file_path, excel_file_path):
    # Load DBC file
    db = cantools.database.load_file(dbc_file_path)

    # Create Excel workbook and worksheet
    wb = Workbook()
    ws = wb.active

    # Write DBC data to Excel
    for message in db.messages:
        ws.append([message.name, message.frame_id, message.length, message.cycle_time])

        for signal in message.signals:
            ws.append(["", signal.name, signal.start, signal.length, signal.byte_order, signal.is_signed,
                       signal.scale, signal.offset, signal.minimum, signal.maximum])

    # Save Excel file
    wb.save(excel_file_path)

if __name__ == "__main__":
    dbc_file_path = "path/to/your/file.dbc"  # Replace with the actual DBC file path
    excel_file_path = "path/to/your/output.xlsx"  # Replace with the desired Excel output path

    read_dbc_and_save_to_excel(dbc_file_path, excel_file_path)


你可能感兴趣的:(python,CICT,python,excel,开发语言)