Sin descripción

test_xls.py 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from openpyxl import load_workbook
  2. from datetime import datetime
  3. # Define the data
  4. data = {
  5. "customer": "xxxx",
  6. "inspect_date": "2025-01-15",
  7. "lot_no": "12345",
  8. "size": "Large",
  9. "pcs": "10 pcs",
  10. "spec": "Spec-A",
  11. "d1_act": "10",
  12. "d2_act": "0", # Adjust this to test hiding `No.2` table
  13. }
  14. # Load the Excel template
  15. template_path = "./hardness.xlsx" # Replace with your template file path
  16. workbook = load_workbook(template_path)
  17. sheet = workbook.active
  18. # Replace placeholders with actual values
  19. for row in sheet.iter_rows():
  20. for cell in row:
  21. if cell.value and isinstance(cell.value, str) and cell.value.startswith("<") and cell.value.endswith(">"):
  22. placeholder = cell.value.strip("<>")
  23. if placeholder in data:
  24. cell.value = data[placeholder]
  25. # Hide `No.2` table if `d2_act` is 0
  26. if data.get("d2_act") == "0":
  27. # Adjust the range to the actual No.2 table location in your template
  28. table_start_row = 20 # Replace with the actual start row of the No.2 table
  29. table_end_row = 25 # Replace with the actual end row of the No.2 table
  30. table_start_col = 1 # Starting column for the table
  31. table_end_col = 5 # Ending column for the table
  32. # Clear only non-merged cells
  33. sheet.row_dimensions.group(24, 28, hidden=True)
  34. # Save the updated file with a timestamp
  35. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  36. output_path = f"hardness_filled_{timestamp}.xlsx"
  37. workbook.save(output_path)
  38. print(f"File saved as {output_path}")