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


    0x00 安装Pandas和OpenPyXL

    pip install pandas
    
    pip install openpyxl
    
    • 1
    • 2
    • 3

    0x01 Encoding

    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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
  • 相关阅读:
    洛谷 P1049 [NOIP2001 普及组] 装箱问题题解
    数据结构之单链表
    使用python中turtle的绘制简单图形
    1. MAC 安装 goland 和 go
    K8s种的service配置
    hive SQL谓词下推
    Flutter开发笔记 —— 语音消息功能实现
    链式队列的基本操作与实现(数据结构与算法)
    【每日一题】535. TinyURL 的加密与解密
    standard_init_linux.go:211: exec user process caused “exec format error“
  • 原文地址:https://blog.csdn.net/Love_XiaoQinEr/article/details/133954640