当前位置: 代码网 > it编程>前端脚本>Python > pandas实现将excel导出到yaml文件中

pandas实现将excel导出到yaml文件中

2025年12月26日 Python 我要评论
本文介绍了一个将excel文件转换为yaml格式的工具函数。该工具需要安装pandas和pyyaml库,主要功能包括:读取excel表格数据,处理空值和日期格式,并将结构化数据输出为yaml文件。核心

本文介绍了一个将excel文件转换为yaml格式的工具函数。该工具需要安装pandas和pyyaml库,主要功能包括:读取excel表格数据,处理空值和日期格式,并将结构化数据输出为yaml文件。

核心函数excel_to_yaml()接收excel路径、输出yaml路径和可选表名参数,通过pandas读取数据后转换为字典列表,最后使用yaml.dump()写入文件。该工具可方便地将表格数据转换为更适合配置使用的yaml格式。

首先需要安装依赖:

pip install pandas
pip install pyyaml

工具函数如下:

import pandas as pd
import yaml


def excel_to_yaml(excel_path, output_yaml_path, excel_sheet_name=0):
    """
    将excel文件转换为yaml文件
    :param excel_path: excel文件路径
    :param output_yaml_path: 输出yaml文件路径
    :param excel_sheet_name: excel文件中的表名,默认为0(第一个表)
    """
    df = pd.read_excel(excel_path, sheet_name=excel_sheet_name)
    data_list = df.to_dict('records')
    for record in data_list:
        for key, value in record.items():
            if pd.isna(value):  # 处理空值
                record[key] = none
            elif hasattr(value, 'strftime'):  # 处理日期时间对象
                record[key] = value.strftime('%y-%m-%d')
    with open(output_yaml_path, 'w', encoding='utf-8') as yaml_file:
        yaml.dump(data_list, yaml_file, allow_unicode=true, sort_keys=false)


def main():
    excel_path = "指数列表.xlsx"
    output_yaml_path = "out_yaml.yaml"
    excel_to_yaml(excel_path, output_yaml_path)


if __name__ == '__main__':
    main()

方法补充:

1.python读取excel内容写入yaml文件

使用python将excel文件内容写入yaml文件的过程包括以下几个步骤:

  • 使用openpyxl模块读取excel文件;
  • 将excel表格数据转换成python对象;
  • 将python对象转换成yaml字符串;
  • 将yaml字符串写入yaml文件。

完整代码

import openpyxl
import yaml
 
 
xlsx_name = "data.xlsx"
 
# 打开excel文件
wb = openpyxl.load_workbook(xlsx_name)
sheet = wb.active
 
# 读取excel表格数据并存储为python对象
data = {'data': []}
for row in sheet.iter_rows(min_row=2, values_only=true):
    item = {'name': row[0], 'age': row[1], 'email': row[2]}
    data['data'].append(item)
 
 
for i in data['data']:
    print(i)
 
# 将python对象转换成yaml字符串
yaml_data = yaml.dump(data)
 
# 将yaml字符串写入yaml文件
with open('data.yaml', 'w') as file:
    file.write(yaml_data)
 
# 读取yaml文件内容
with open('data.yaml', 'r') as file:
    datar = yaml.load(file, loader=yaml.fullloader)
print(datar)
 
 
'''
{'name': 's1', 'age': 22, 'email': 's1@xcel.com'}
{'name': 's2', 'age': 23, 'email': 's3@xcel.com'}
{'name': '宋', 'age': 24, 'email': 's4@xcel.com'}
{'data': [{'age': 22, 'email': 's1@xcel.com', 'name': 's1'}, {'age': 23, 'email': 's3@xcel.com', 'name': 's2'}, {'age': 24, 'email': 's4@xcel.com', 'name': '宋'}]}
'''

2.python脚本实现将excel 文件中的数据导入yaml文件

这是一个python脚本,用于将excel文件转换为yaml格式。脚本读取excel工作簿中的数据,创建一个有序字典结构,并填充测试用例的相关信息,如类型、名称、描述、路径等。最终,它将这个字典写入yaml文件,实现了测试用例的自动化转换。

import yaml
import os
from collections import ordereddict
import openpyxl


class testcases_protocol:

    """this script is to convert excel file to yaml file."""

    def __init__(self,file_name,yaml_name):
        self.file_name = file_name
        self.yaml_name = yaml_name
        self.final_dict = ordereddict()
        self.new_pltform_dic = ordereddict()


    def create_dict(self):
        wb = openpyxl.load_workbook(self.file_name)
        sheet_names = wb.sheetnames
        count_cases=[]
        for sheet_name in sheet_names:
            print(sheet_name)
            ws = wb[sheet_name]
            max_row = ws.max_row
            count_cases.append(max_row-2)
            for n_row in range(3,max_row+1):
                script_type = ws.cell(row=n_row, column=1).value
                script_name = ws.cell(row=n_row, column=2).value
                description = ws.cell(row=n_row, column=3).value
                script_path = ws.cell(row=n_row, column=4).value

                if not script_type:
                    continue
                else:
                    self.new_pltform_dic[script_name] = ordereddict()
                    self.new_pltform_dic[script_name].update({
                        "type":script_type,
                        "loop":'1',
                        "duration":'60',
                        "description":description,
                        "script_path":script_path,
                        "parameters": "default"
                    })
                # for k,v in new_pltform_dic.items():
                #   print(k,':',v)
        with open(self.yaml_name, 'w') as f:
            yaml.dump(self.new_pltform_dic, f)
            print(sum(count_cases))


if __name__=='__main__':
    case1 = testcases_protocol('test.xlsx','new.yaml')
    case1.create_dict()

到此这篇关于pandas实现将excel导出到yaml文件中的文章就介绍到这了,更多相关pandas excel导出到yaml内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com