打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
多SHEET页的EXCEL文件批量合并

前段时间工作中遇到需要将多个excel合并,且每个excel都有多个sheet页

在CSDN也没搜到特别简洁的代码,其实就两个循环的事情

不过还好,站在巨人的肩膀上看的远,就集各家所长,为己所用

顺带写了带图形界面的,顺带用PyQt5打了个包,上代码

  1. import sys
  2. from PyQt5 import QtCore, QtWidgets, QtGui
  3. from PyQt5.QtWidgets import *
  4. import pandas as pd
  5. import os
  6. import xlrd
  7. def excel_merge(path, col, out):
  8. fns = os.listdir(path)
  9. dfs = pd.DataFrame()
  10. for fn in fns:
  11. excel_path = path + fn
  12. wb = xlrd.open_workbook(excel_path)
  13. sheets = wb.sheets()
  14. for sheet in sheets:
  15. df = pd.read_excel(excel_path, sheet_name=sheet, index=False)
  16. new_df = df.loc[:, col]
  17. dfs = dfs.append(new_df)
  18. dfs.dropna(axis=0, how='any', inplace=True)
  19. dfs.to_excel(out, index=None)
  20. class Test():
  21. def window(self, w):
  22. # 设置主窗口的坐标和大小
  23. w.setGeometry(500, 300, 800, 300)
  24. w.setWindowTitle('Excel文件批量合并')
  25. w.setWindowIcon(QtGui.QIcon('1.jpg'))
  26. # 设置文本和输入框的 坐标以及大小
  27. self.intext = QtWidgets.QLabel(w)
  28. self.intext.setGeometry(QtCore.QRect(60, 20, 120, 45))
  29. self.intext.setText('源文件路径:')
  30. self.inbtn = QtWidgets.QLineEdit(w)
  31. self.inbtn.setGeometry(QtCore.QRect(200, 30, 500, 30))
  32. # 设置文本和输入框的 坐标以及大小
  33. self.outext = QtWidgets.QLabel(w)
  34. self.outext.setGeometry(QtCore.QRect(60, 70, 120, 45))
  35. self.outext.setText('新文件路径:')
  36. self.outbtn = QtWidgets.QLineEdit(w)
  37. self.outbtn.setGeometry(QtCore.QRect(200, 80, 500, 30))
  38. # 设置文本和输入框的 坐标以及大小
  39. self.coltext = QtWidgets.QLabel(w)
  40. self.coltext.setGeometry(QtCore.QRect(60, 120, 120, 45))
  41. self.coltext.setText('需保留的列:')
  42. self.colbtn = QtWidgets.QLineEdit(w)
  43. self.colbtn.setGeometry(QtCore.QRect(200, 130, 500, 30))
  44. # 添加按钮坐标 和大小, 绑定按钮点击事件
  45. self.subtn = QtWidgets.QPushButton(w)
  46. self.subtn.setGeometry(QtCore.QRect(350, 200, 100, 30))
  47. self.subtn.setText('执行合并')
  48. self.subtn.clicked.connect(self.merge)
  49. self.subtn.clicked.connect(w.close)
  50. w.show()
  51. def merge(self):
  52. path = self.inbtn.text()
  53. col = list(self.colbtn.text().split(','))
  54. out = self.outbtn.text()
  55. excel_merge(path, col, out)
  56. # 设置警告弹窗内容
  57. app = QApplication(sys.argv)
  58. msg_box = QMessageBox(QMessageBox.Warning, '通知', '合并完成')
  59. app.exit(msg_box.exec_())
  60. if __name__ == '__main__':
  61. app = QtWidgets.QApplication(sys.argv)
  62. w = QtWidgets.QWidget()
  63. ui = Test()
  64. ui.window(w)
  65. sys.exit(app.exec_())
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
PyQt实现读取MySql数据库表数据将其显示在TableWidget并保存为excel表格
用python制作AI欢乐斗地主出牌器,赢欢乐豆,实现财富自由
python使用Qt界面以及逻辑实现
Python实现Windows定时关机
python+opencv+dlib+pyqt5人脸识别实践
pyqt4制作透明无边框窗体
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服