import logging
import datetime
import os
import sys
import openpyxl
import tkinter as Tk# 将该表的数据汇总到另一张表
excelFromFile = r'C:\Users\Administrator\Desktop\excel\book2.xlsx'
# 将其他表的数据汇总到这个表
excelToFile = r'C:\Users\Administrator\Desktop\excel\book1.xlsx'
# 如果该列有指定则仅更新此列数据
referColumn = ['G', '张三']
# 需要更新的数据列
combineColumn = ['H', 'I']
# 日志默认文件名
logFileDefaultName = 'option.log'# 工作表类
class excel:# 文件名fileName = ''# 打开的工作簿workBook = ''# 当前活动的工作表currentSheet = ''# 是否被打开active = Falsedef __init__(self, fileName):self.fileName = fileNamedef open(self, sheetName):try:self.workBook = openpyxl.load_workbook(self.fileName)self.currentSheet = self.workBook[sheetName]except Exception as err:# exType, exValue, exTrace = sys.exc_info()# logging.error(str(exType) + str(exValue))logging.error(err)return Falseself.active = Truereturn Truedef close(self):self.workBook.save(self.fileName)self.active = False# 设置当前活动的工作表def SetCurrentSheet(self, sheetName):self.currentSheet = self.workBook[sheetName]# 获取最大行和列def GetMaxRowAndColumn(self):maxRow = self.currentSheet.max_rowmaxColumn = self.currentSheet.max_columnreturn maxRow, maxColumn# 将另一个excel表的指定列合并到指定列def Combine(self, excelFrom, referColumn, combineColumn):# 参数检查#比较两张表的行列匹配maxRowColumnFrom = excelFrom.GetMaxRowAndColumn()maxRowColumnTo = self.GetMaxRowAndColumn()if maxRowColumnFrom != maxRowColumnTo:logging.error("from(%d , %d) is not equal to(%d , %d) row and column,"\%(maxRowColumnFrom[0], maxRowColumnFrom[1], \maxRowColumnTo[0], maxRowColumnTo[1]))return False# 比较要合并的列是否超过表的最大列# 开始合入for i in range(maxRowColumnTo[0]):# logging.debug(type(referColumn[0]))match = self.currentSheet.cell(row=i+1, column=referColumn[0]).valueif match != referColumn[1]:continuefor column in combineColumn:value = excelFrom.currentSheet.cell(row=i+1, column=column).valueself.currentSheet.cell(row=i+1, column=column).value = value# 写入一行就保存文件self.workBook.save(self.fileName)logging.debug("combine row : %d" %(i+1))# 合入完成logging.debug('combine finish')# 将字母列转换为数字列
def ConvertExcelStrToNumColumn(column):i = 0for o in column:column[i] = openpyxl.utils.column_index_from_string(o)i += 1
def GetExcelColumnNumFromStr(str):return openpyxl.utils.column_index_from_string(str)def ConvertReferColumn(column):column[0] = openpyxl.utils.column_index_from_string(column[0])# 日志配置
def logConfig(level, iscover = True):logFileName = logFileDefaultNameif iscover:# 如果文件存在则删除if os.path.exists(logFileName):os.remove(logFileName)else:time = datetime.datetime.now()logFileName = "%02d%02d%02d_%02d%02d%02d.%03d"\%(time.year, time.month, time.day,\time.hour, time.minute, time.second,\time.microsecond) + '.log'format = '%(asctime)s -%(levelname)s- %(message)s'logging.basicConfig(filename=logFileName, level=level, format=format)# 获取参数
def GetParamFromKeyBoard(fromFile, toFile, refer, combine):str = ''while True:fromFile = input('请输入需要合入的文件名(*.xlsx):')if not os.path.exists(fromFile):print('文件不存在,请重新输入')continuebreakwhile True:toFile = input('请输入合入文件名:')if not os.path.exists(toFile):print('文件不存在,请重新输入')continuebreakwhile True:str = input('请输入参考列(G,张三):')list = str.split(',')if len(list) != 2:print('参考列输入有误请重新输入:')continuerefer.clear()for o in list:refer.append(o)breakstr = input('请输入需要合入的列(H,I,J):')combine.clear()for o in str.split(','):combine.append(o)if __name__ == '__main__':ret = ''# 获取参数GetParamFromKeyBoard(excelFromFile, excelToFile, referColumn, combineColumn)# print(combineColumn)# 日志记录配置logConfig(logging.DEBUG)logging.debug("start autocombine excel ".center(30, '-'))while True:# 1.获取参数# 2.校验参数ConvertExcelStrToNumColumn(combineColumn)ConvertReferColumn(referColumn)logging.debug("combineColumn:" + str(combineColumn))excelFrom = excel(excelFromFile)excelTo = excel(excelToFile)# 3.加载excelret = excelFrom.open('Sheet1')if not ret:breakret = excelTo.open('Sheet1')if not ret:breaklogging.debug("load excel %s from and to success" %('sheet1'))excelTo.Combine(excelFrom, referColumn, combineColumn)# 执行到最后也得退出breakif excelFrom.active:excelFrom.close()if excelTo.active:excelTo.close()logging.debug("end autocombine excel".center(30, '='))if __name__ != '__main__':for i in range(10):print(i)

背景:

工作中好几个人同时修改一张excel表然后各自同步提交,这个时候如果用SVN,除了第一个提交的人不冲突其余的人都会出现冲突。网上也找了些办法感觉靠谱点的就是用excel自带的共享工作簿实现协同。但是具体操作感觉挺麻烦的。 那正好之前了解了一下python,所以正好用python 解决了这个问题。

解决思路:

因为主要解决的是将表1 指定行的指定列 合入到表2对应的单元格中,因此这个翻译出来就是四个参数:

1.excelFromName : 表1的文件名

2.excelToName :表2的文件名

3.referColumn : 指定行特征,这里我用的是行的指定列为指定值 则符合行特征

4.combineColumn :需要合入的列,当然这个列可以不连续

测试:

能解决遇到的问题,就是需要手动输入以上四个参数,没有图形化界面,操作不太方便

写在最后:

如果读者有好的解决办法,欢迎交流。。。

Python实现excel表合入相关推荐

  1. Python处理Excel表中单元格带有换行的数据

    Python处理Excel表中单元格带有换行的数据 文章目录 Python处理Excel表中单元格带有换行的数据 问题样式 实例问题 实例实现代码 实例结果 问题样式 在数据处理过程中常常会遇到这样一 ...

  2. python怎么导入sql数据库,##使用python将excel表中数据导入sql server数据库

    如何用python将excel数据导入到postgresql数据库中 把excel表格另存为csv文件 python将exce文件含有多个sheet同时l导入sqlserver数据库 需要使用xlrd ...

  3. python 读取excel表数据_5分钟学会用Python 读取Excel

    5分钟学会用Python 读取Excel 日常办公使用频率最高的软件非Excel莫属了,如果我们遇到需要导入别人的Excel进行后续数据分析.读取内容等操作,我们该怎么办呢? 测试开发哥哥说:莫要慌, ...

  4. python 汇总excel表_【Python】Word表格汇总Excel

    年底了,又到了汇总总结的时候.由于朋友要整理一千多个word表格到excel表上,帮她写了个程序,后来又将它改成更为通用的版本. 其实在这个过程中我找到了有人制作的VBA版,但是使用过程中有BUG [ ...

  5. python合并excel表数据_23.python之excel多表合并

    关于python的应用办公中很常见,尤其是对于数量较多的重复性操作.本节课要做的是将多张excel表中的信息合并到一张excel表中. 新建一个文件夹名为[merge],里面放入三个名为[销售订单信息 ...

  6. python打开excel表_如何用python打开excel

    最近看到好几次群里有人问xlwt.wlrd的问题,怎么说呢,如果是office2007刚出来,大家用xlsx文件用不习惯,还可以理解,这都10年过去了喂,就算没有进化到office2016,还在用of ...

  7. python打开excel表_Python启动Excel

    通过简单的实例实现Python与Excel程序实现交互控制. 需要安装pywin32,根据自己的实际情况选择下载版本 引入组件import win32com.client, win32process ...

  8. python 读取excel表数据获取坐标_python读取并定位excel数据坐标系详解

    测试数据:坐标数据:testExcelData.xlsx 使用python读取excel文件需要安装xlrd库: xlrd下载后的压缩文件:xlrd-1.2.0.tar.gz 解压后再进行安装即可,具 ...

  9. python中Excel表的读写改详解

    ## python中Excel中的读import xlrd#先导入xlrd模块 excel = xlrd.open_workbook('1.xls')# 打开xls文件 print(excel) # ...

最新文章

  1. 重庆2021级春招高考成绩查询,2021重庆高考成绩查询入口
  2. [download]-软件下载地址-百度网盘
  3. hdu2089 不要62 数位dp
  4. flask项目从本地迁移到服务器上遇到net::ERR_CONNECTION_R问题
  5. static class 静态类(Java)转
  6. 开源项目推荐:CNC+CRC/SoftPLC/OpenCASCADE/CAD/CAM
  7. LeetCode 排序和搜索简单部分 Python实现
  8. 计算机表格乘法表,教你用Excel制作乘法表,方法奉上
  9. LINUX 中htop的安装
  10. [日推荐] 『地铁查询』全国地铁尽在手中,不怕迷路!
  11. 计算机组成原理CPUCLK什么,计算机组成原理之CPU原理.pdf
  12. 万字专栏总结 | 离线强化学习(OfflineRL)总结(原理、数据集、算法、复杂性分析、超参数调优等)...
  13. 如何导出某人微信聊天记录到电脑
  14. 如何创建表以及设计表需要注意什么,oracle五种限制
  15. 一个简单的连续变焦红外镜头的从零开始的设计过程(zemax)(二)进一步优化,公差分析
  16. html5项目改造Vue工程化
  17. 第八届蓝桥杯Java A组决赛第一题
  18. FastJson - JSONObject 如何设置成有序?(如:LinkedHashMap)
  19. ssh访问控制,封杀ip,防止暴力破解
  20. 一款牛逼的Java工具类库,GitHub星标11.6k+

热门文章

  1. 【Linux】虚拟机VMware的Ubuntu使用vi指令的方向键和backspace空格键乱码
  2. android:手机与BLE-CC41-A蓝牙模块通信
  3. mysql gtidpurged_7. MySQL复制全解析 Part 7 gtid_next和gtid_purged 系统变量解析
  4. pandas读取csv文件UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xca in position 37: invalid contin
  5. Linux预科知识篇之认识计算机
  6. AVFoundation(一)
  7. Android 收银机Wifi 连接厨房厨单打印机
  8. java代理模式(java代理模式和适配器模式)
  9. Java开发导入腾讯地图描点_腾讯地图点聚合开发-实现地图找房功能
  10. csv反序列化_对象的反序列化