conformity.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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(file_path, print_path):
  17. try:
  18. # 加载模板文件
  19. template_path = os.path.join('app', 'utils', 'excelmerge', '国网上海电力整合模版.xlsx')
  20. template_excel = load_workbook(template_path)
  21. template_sheets = {sheet.title: sheet for sheet in template_excel}
  22. source_files = [f for f in os.listdir(file_path) if f.endswith('.xlsx') and not f.startswith('~$')]
  23. for file in source_files:
  24. source_path = os.path.join(file_path, file)
  25. source_excel = load_workbook(source_path)
  26. # 动态获取工作表
  27. source_sheets = {sheet.title: sheet for sheet in source_excel}
  28. for name in template_sheets:
  29. if name in source_sheets:
  30. clear_blank_rows(source_sheets[name])
  31. for name, start_row in [('技术监督工作统计表', 4), ('技术监督告(预)警单统计表', 3),
  32. ('投产前技术监督报告统计表', 3), ('技术监督细则完善建议', 4),
  33. ('典型经验交流', 3)]:
  34. if name in source_sheets and name in template_sheets:
  35. copy_data(source_sheets[name], template_sheets[name], start_row)
  36. source_excel.close()
  37. for name, start_row in [('技术监督工作统计表', 4), ('技术监督告(预)警单统计表', 3),
  38. ('投产前技术监督报告统计表', 3), ('技术监督细则完善建议', 4),
  39. ('典型经验交流', 3)]:
  40. if name in template_sheets:
  41. last_row = template_sheets[name].max_row
  42. for i in range(start_row, last_row + 1):
  43. template_sheets[name].cell(row=i, column=1).value = i - start_row + 1
  44. timestamp = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
  45. output_path = os.path.join(print_path, f'{timestamp}.xlsx')
  46. template_excel.save(output_path)
  47. template_excel.close()
  48. return True
  49. except Exception as e:
  50. print(f"读取数据发生错误: {e}")
  51. return False