ExcelWriter 使用 openpyxl 引擎忽略 date_format 参数

huangapple go评论94阅读模式
英文:

ExcelWriter using openpyxl engine ignoring date_format parameter

问题

我已经阅读了很多关于这个问题的答案,但当我运行我的代码时,我得到的结果不同。

我正在使用pandas 2.0.0和Python 3.9上的openpyxl 3.1.2。

这是我的问题的一个简化示例,即I无法让ExcelWriter遵守我的日期格式选择。我试图将一个新的工作表附加到现有的Excel .xlsx文件中。

  1. import pandas as pd
  2. import datetime
  3. filePath = 'c:\\temp\\myfile.xlsx'
  4. writer = pd.ExcelWriter(filePath, mode='a', engine='openpyxl', if_sheet_exists='replace', date_format='DD/MM/YYYY')
  5. df = pd.DataFrame([datetime.date(2023, 4, 7)], columns=['Date'])
  6. df.to_excel(writer, sheet_name='Data')
  7. writer.close()

在Excel中的结果如下图所示:

ExcelWriter 使用 openpyxl 引擎忽略 date_format 参数

我已经明确将数据框中的值的类型设置为datetime.date。我尝试使用datetime_format,或者两者一起使用,但都没有成功。

我还尝试了xlsxwriter,但似乎这个引擎不允许追加到现有的工作簿。

英文:

I have read quite a few answers on this, but when I run my code I don't get the same result.

I am using pandas 2.0.0 and openpyxl 3.1.2 on Python 3.9

This is a reduced example of my issue, which is that I can't get the ExcelWriter to respect my choice of date format. I am trying to append a new sheet to an existing Excel .xlsx file.

  1. import pandas as pd
  2. import datetime
  3. filePath = 'c:\\temp\\myfile.xlsx'
  4. writer = pd.ExcelWriter(filePath,mode='a',engine='openpyxl',if_sheet_exists='replace',date_format='DD/MM/YYY')
  5. df = pd.DataFrame([datetime.date(2023,4,7)],columns=['Date'])
  6. df.to_excel(writer,sheet_name='Data')
  7. writer.close()

The result in Excel is this:

ExcelWriter 使用 openpyxl 引擎忽略 date_format 参数

I have explicitly set the type of the value in the dataframe to be datetime.date. I have tried using datetime_format or indeed both together but to no avail.

I have also tried xlsxwriter but it seems this engine does not allow appending to an existing workbook.

答案1

得分: 2

这似乎是OpenpyxlWriter的实现中的一个错误:

  1. class OpenpyxlWriter(ExcelWriter):
  2. _engine = "openpyxl"
  3. _supported_extensions = (".xlsx", ".xlsm")
  4. def __init__(
  5. self,
  6. path: FilePath | WriteExcelBuffer | ExcelWriter,
  7. engine: str | None = None,
  8. date_format: str | None = None,
  9. datetime_format: str | None = None,
  10. mode: str = "w",
  11. storage_options: StorageOptions = None,
  12. if_sheet_exists: str | None = None,
  13. engine_kwargs: dict[str, Any] | None = None,
  14. **kwargs,
  15. ) -> None:
  16. # 使用 openpyxl 模块作为 Excel 写入器。
  17. from openpyxl.workbook import Workbook
  18. engine_kwargs = combine_kwargs(engine_kwargs, kwargs)
  19. super().__init__(
  20. path,
  21. mode=mode,
  22. storage_options=storage_options,
  23. if_sheet_exists=if_sheet_exists,
  24. engine_kwargs=engine_kwargs,
  25. )

要修复,将以下内容添加到 super().__init__() 调用中:

  1. date_format=date_format,
  2. datetime_format=datetime_format,
英文:

This appears to be a bug in the implementation of OpenpyxlWriter:

  1. class OpenpyxlWriter(ExcelWriter):
  2. _engine = "openpyxl"
  3. _supported_extensions = (".xlsx", ".xlsm")
  4. def __init__(
  5. self,
  6. path: FilePath | WriteExcelBuffer | ExcelWriter,
  7. engine: str | None = None,
  8. date_format: str | None = None,
  9. datetime_format: str | None = None,
  10. mode: str = "w",
  11. storage_options: StorageOptions = None,
  12. if_sheet_exists: str | None = None,
  13. engine_kwargs: dict[str, Any] | None = None,
  14. **kwargs,
  15. ) -> None:
  16. # Use the openpyxl module as the Excel writer.
  17. from openpyxl.workbook import Workbook
  18. engine_kwargs = combine_kwargs(engine_kwargs, kwargs)
  19. super().__init__(
  20. path,
  21. mode=mode,
  22. storage_options=storage_options,
  23. if_sheet_exists=if_sheet_exists,
  24. engine_kwargs=engine_kwargs,
  25. )

To fix, add

  1. date_format=date_format,
  2. datetime_format=datetime_format,

to the super().__init__() call:

  1. super().__init__(
  2. path,
  3. date_format=date_format,
  4. datetime_format=datetime_format,
  5. mode=mode,
  6. storage_options=storage_options,
  7. if_sheet_exists=if_sheet_exists,
  8. engine_kwargs=engine_kwargs,
  9. )

huangapple
  • 本文由 发表于 2023年4月7日 01:04:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952042.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定