【问题标题】:Numbers are being converted to date format automatically while writing in Excel sheet using python Openpyxl使用 python Openpyxl 在 Excel 表中写入时,数字会自动转换为日期格式
【发布时间】:2019-09-14 17:03:12
【问题描述】:

我正在对我的一份报告进行自动化处理。但是,当我使用 openpyxl 将列表中的值(即“摘要”)复制到 Excel 中名为“摘要”的工作表之一时。它会自动将数字转换为日期。当我在 excel 中检查格式单元格时,单元格将转换为自定义字段。

我尝试了代码cell.number_format='General'。但它也不起作用

'summary' 是我需要在名为 'Summary' 的 Excel 表中写入的列表

>>>summary

[11, '19', 322, 2460, 317, 2413, 318, 4, 9, 47, 2370, 2370, 0, 0, '2455']

我正在执行的完整代码:

wb_obj=openpyxl.load_workbook('test.xlsx')

sheet_sumary=wb_obj['Summary']

max_col1 = sheet_sumary.max_column

m_row1 = sheet_sumary.max_row

for j in range(1,max_col1+1):

    cell=sheet_sumary.cell(row=m_row1+1,column=j)

    cell.value= (summary[j-1])

    cell.number_format='General'

excel 中的预期结果:

Date    Trace collection Hour   Total SMK Nodes Total SMK Cells Total Nodes TA Available    Total cells TA Available

3-Sep-19    19  322 2460    317 2413

excel中的实际结果:

Date    Trace collection Hour   Total SMK Nodes Total SMK Cells Total Nodes TA Available    Total cells TA Available

11/Jan/00   19  17/Nov/00   25/Sep/06   12/Nov/00   9/Aug/06

上面是某个列的示例,在这里我们可以看到我的数据被转换为某种任意日期格式,例如列“Total SMK Nodes”,其值应为 322,但在写入时此数字转换为 '17/Nov/00'进入excel。

【问题讨论】:

  • 以后请努力使用正确的格式(有一个工具栏和帮助图标可以帮助您)。我已经为你修好了,但是当代码和结果只是扔在那里时,问题是非常难以阅读的,而且如果他们不得不通过类似的东西来解决你的问题,很多人会无视你的问题。
  • 非常感谢...我不知道。

标签: python openpyxl


【解决方案1】:

这是 Excel 坚持对其用户施加的已知 PITA。您可以采取一些措施来减轻这种影响。

  1. 看起来您的Summary 行示例具有int 和str 值的奇怪组合。我建议您在设置单元格时将它们转换为适当的值。
  2. 不要使用常规格式。如果您想要一个数字单元格,请使用实际的 Number 格式化类。 General 是 Excel 的默认设置,它几乎可以为所欲为。

【讨论】:

  • 当我使用cell.number_format='Number'。打开excel时出现以下错误。 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><logFileName>error114960_05.xml</logFileName><summary>Errors were detected in file 'C:\automation\TA Stats tracker_SMK_3rd_Sep19.xlsx'</summary><repairedRecords><repairedRecord>Repaired Records: Format from /xl/styles.xml part (Styles)</repairedRecord></repairedRecords></recoveryLog>
  • @RoushanAnand:我的猜测是您正在尝试将字符串写入数字字段。尝试将值设置为int(value) 而不仅仅是value。
  • 我已将代码更改为cell.value=int(summary[j-1])。还尝试仅写入 int 值并手动删除任何字符串。但仍然得到同样的错误。 excel We found a problem with some content in test.xlsx. Do you want to recover as much as we can? if you trust the sourceof this workbook, click yes 抛出的消息,在挖掘时我收到了我在上面的评论中提到的错误。
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2014-09-18
  • 2015-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多