python pandas excel读取和写入,以及颜色设置

您所在的位置:网站首页 怎样给表格边框添加颜色填充 python pandas excel读取和写入,以及颜色设置

python pandas excel读取和写入,以及颜色设置

2023-07-20 08:03| 来源: 网络整理| 查看: 265

原因

这几天策划做多语言翻译,因为外包给回来的翻译文件和原来的文件顺序是错乱的,而现在新的配置文件又有增删。本着技术解放生产力的想法和没事找事做原则,强行给自己加了个需求。用python写一个工具,将两边的内容进行对比,生成一个新的文件,并用颜色标注差异部分。

环境 Python 3.9.7pandasosre import pandas as pd import os import sys import re import time csv读取 fResult = re.findall("^.*\.(\w+)$", filePath) if (len(fResult) == 0): return fileType = fResult[0] if fileType == "csv":#简单判断下文件类型 data = pd.read_csv(filePath, None, header=None, engine='python') for jKey in data.keys(): jRow = data[jKey] for kIndex in range(1, len(jRow)): kContent = jRow[kIndex] #获取到单元格内容 ...... excel读取 data = pd.read_excel(filePath, None, header=None) #设置header才能读取到第一行 for jKey in data.keys(): jSheetData = data[jKey] totalRow = len(jSheetData.index) #总行数 for kRow in range(1, totalRow):#从第二行开始遍历 oneRow = jSheetData.loc[kRow][0:] for kIndex in range(len(oneRow)): kContent = oneRow[kIndex] #获取到单元格内容 ...... excel单元格颜色设置以及excel写入 def style_apply(content, colors, back_ground=''): if content != None and content in colors.keys(): return 'background-color: ' + colors[content] return back_ground def style_color(df, colors): return df.style.applymap(style_apply, colors=colors) resultMap = {'A':['test1', 'test2', 'test3'], 'B':['test2', 'test4', 'test5']} #写入数据结构示例 filePath = "{}.xlsx".format(int(time.time()*1000)) compare_pd=pd.DataFrame(resultMap) writer = pd.ExcelWriter(filePath, engine='openpyxl')#创建数据存放路径 colors = {'test1':'#ff0000', 'test2':'#ffff00'} style_df = style_color(compare_pd, colors) style_df.to_excel(writer, header=None, index=False, sheet_name='compare') writer.save()#文件保存 writer.close() os.startfile(filePath)# 使用默认程序自动打开新生成的excel文件 参考链接

https://www.yisu.com/zixun/234627.html



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3