conformity.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from openpyxl import load_workbook
  2. from datetime import datetime
  3. import os
  4. def clear_blank_rows(sheet):
  5. last_row = sheet.max_row
  6. for row in range(last_row, 1, -1):
  7. if all(cell.value is None or cell.value == '' for cell in sheet[row]):
  8. sheet.delete_rows(row)
  9. def copy_data(source_sheet, target_sheet, start_row):
  10. for row in range(start_row, source_sheet.max_row + 1):
  11. a_cell_value = source_sheet.cell(row=row, column=1).value
  12. if isinstance(a_cell_value, (int, float)) and any(
  13. source_sheet.cell(row=row, column=col).value for col in range(4, source_sheet.max_column + 1)):
  14. target_sheet.append(
  15. [source_sheet.cell(row=row, column=col).value for col in range(1, source_sheet.max_column + 1)])
  16. def run_conformity():
  17. try:
  18. # 加载模板文件
  19. template_path = os.path.join('app', 'utils', 'excelmerge', '国网上海电力整合模版.xlsx')
  20. template_excel = load_workbook(template_path)
  21. EXCEL_FILES_PATH = os.path.join('data', 'output')
  22. template_sheets = {sheet.title: sheet for sheet in template_excel}
  23. source_folder = os.path.join('data', 'source')
  24. source_files = [f for f in os.listdir(source_folder) if f.endswith('.xlsx') and not f.startswith('~$')]
  25. for file in source_files:
  26. source_path = os.path.join(source_folder, file)
  27. source_excel = load_workbook(source_path)
  28. # 动态获取工作表
  29. source_sheets = {sheet.title: sheet for sheet in source_excel}
  30. for name in template_sheets:
  31. if name in source_sheets:
  32. clear_blank_rows(source_sheets[name])
  33. for name, start_row in [('技术监督工作统计表', 4), ('技术监督告(预)警单统计表', 3),
  34. ('投产前技术监督报告统计表', 3), ('技术监督细则完善建议', 4),
  35. ('典型经验交流', 3)]:
  36. if name in source_sheets and name in template_sheets:
  37. copy_data(source_sheets[name], template_sheets[name], start_row)
  38. source_excel.close()
  39. for name, start_row in [('技术监督工作统计表', 4), ('技术监督告(预)警单统计表', 3),
  40. ('投产前技术监督报告统计表', 3), ('技术监督细则完善建议', 4),
  41. ('典型经验交流', 3)]:
  42. if name in template_sheets:
  43. last_row = template_sheets[name].max_row
  44. for i in range(start_row, last_row + 1):
  45. template_sheets[name].cell(row=i, column=1).value = i - start_row + 1
  46. timestamp = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
  47. output_path = os.path.join(EXCEL_FILES_PATH, f'{timestamp}.xlsx')
  48. template_excel.save(output_path)
  49. template_excel.close()
  50. return True
  51. except Exception as e:
  52. print(f"读取数据发生错误: {e}")
  53. return False