多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_())
(0)

相关推荐