Python读取Excel文件中指定的列数并生成CSV文件

0x00 安装Pandas和OpenPyXL

python 复制代码
pip install pandas

pip install openpyxl

0x01 Encoding

python 复制代码
import os
import pandas as pd
import openpyxl
from openpyxl import load_workbook
import csv


def write_dict_to_csv(dict_data, fileName):
    df = pd.DataFrame.from_dict(dict_data)
    # 将DataFrame写入CSV文件
    df.to_csv(fileName, index=False)


def writeCSV(dict_data, fileName):
    # 打开CSV文件
    with open(fileName, 'w', newline='') as file:
        writer = csv.writer(file)

        # writer.writerow(["key", "value"])
        print("====================================")

        # 工况点字典
        msgPoints_dict = {}
        msgPoints_num = 51

        # 遍历字典
        for key, value in dict_data.items():
            print(value)
            # writer.writerow(value)
            if isinstance(value, list):
                for item in value:
                    # 若表格数据为空则过滤掉
                    if isinstance(item, str) and item.startswith('EP') and item is not None:
                        msgPoints_dict[msgPoints_num] = value
                        # writer.writerow(value)
                        msgPoints_num = msgPoints_num + 1

        print("msgPoints_dict_size: " + str(len(msgPoints_dict)))

        for key, value in msgPoints_dict.items():
            print(key, value, end="\n")
            # 检查键值是否以"EP"开头
            if isinstance(value, list) and value and isinstance(value[2], str) and value[2].startswith("EP"):
                # print(value)

                tmp_list = [str(key)]
                tmp_list.extend(value)
                # 写入CSV文件
                # writer.writerow([key, item])
                writer.writerow(tmp_list)

    pass


def main():
    print("=== Read Excel ===")
    fileName = './doc/data.xlsx'

    # 字典类型
    dict_data = {}
    if os.path.exists(fileName):
        # 当前活跃的Sheel页
        wb = load_workbook(fileName)
        print(wb.active)

        shell = wb.active
        # print(ws['B7'].value)
        # print(ws.cell(7, 2).value)
        # rows = ws.rows
        # print(rows)

        columns_to_print = ['B', 'F', 'O']
        index = 1
        for row in shell.iter_rows():
            tmp_list = []
            for col_idx, cell in enumerate(row, start=1):
                column_letter = openpyxl.utils.get_column_letter(col_idx)
                if column_letter in columns_to_print:
                    tmp_list.append(cell.value)
                    # print(cell.value)

            dict_data[index] = tmp_list
            index = index + 1

    writeCSV(dict_data, "output.csv")
    # write_dict_to_csv(dict_data, "msg_points.csv")
    pass


if __name__ == "__main__":
    main()
相关推荐
之歆21 分钟前
Python-正则表达式-信息提取-滑动窗口-数据分发-文件加载及分析器-浏览器分析-学习笔记
python·学习·正则表达式
小庞在加油24 分钟前
Apollo源码架构解析---附C++代码设计示例
开发语言·c++·架构·自动驾驶·apollo
往日情怀酿做酒 V176392963825 分钟前
pytorch的介绍以及张量的创建
人工智能·pytorch·python
豌豆花下猫1 小时前
Python 潮流周刊#110:JIT 编译器两年回顾,AI 智能体工具大爆发(摘要)
后端·python·ai
专注VB编程开发20年1 小时前
各版本操作系统对.NET支持情况(250707更新)
开发语言·前端·ide·vscode·.net
我喜欢就喜欢1 小时前
RapidFuzz-CPP:高效字符串相似度计算的C++利器
开发语言·c++
莫彩1 小时前
【Modern C++ Part7】_创建对象时使用()和{}的区别
开发语言·c++
星光54221 小时前
飞算JavaAI:给Java开发装上“智能引擎”的超级助手
java·开发语言
June bug2 小时前
【Python基础】变量、运算与内存管理全解析
开发语言·python·职场和发展·测试
醇醛酸醚酮酯2 小时前
Qt项目锻炼——TODO(五)
开发语言·qt