file_util.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import os
  2. from typing import Optional
  3. import pandas as pd
  4. class ExcelFile:
  5. def __init__(self, file_path):
  6. # 基于引用 dict_from_json 函数的文件的绝对路径
  7. self._file_path = file_path
  8. self.file = self.read_excel(file_path)
  9. def new_column(self, column_name):
  10. try:
  11. column_index = self.file.columns.get_loc(column_name)
  12. if column_index is None:
  13. self.file[column_name] = ""
  14. self.file.to_excel(self._file_path, index=False)
  15. except Exception as e:
  16. print(f"Unexpected error creating new column: {column_name}")
  17. def new_value(self, row_index, column_name, value):
  18. try:
  19. self.file.at[row_index, column_name] = value
  20. self.file.to_excel(self._file_path, index=False)
  21. except Exception as e:
  22. print(f"Unexpected error creating new column: {column_name}")
  23. @staticmethod
  24. def read_excel(file_path):
  25. try:
  26. df = pd.read_excel(file_path)
  27. except FileNotFoundError:
  28. print(f"File not found: {file_path}")
  29. return None
  30. except Exception as e:
  31. print(f"Unexpected error reading file: {file_path}")
  32. print(str(e))
  33. return None
  34. try:
  35. return df
  36. except Exception as e:
  37. print(f"Unexpected error converting DataFrame to string")
  38. print(str(e))
  39. return None