openpyxl更改同一文件的未更改工作表中列的数字格式

问题描述 投票:0回答:1

我注意到当我使用openpyxl向.xlsx文件添加额外的工作表时,它会自动更改此文件中预先存在的工作表中列的数字格式。

按时间顺序排列,问题如下:

1)我使用“时间戳”格式手动记录此预先存在的表格列中某些感兴趣事件的日期和时间。我通过Excel将列格式设置为Date(格式代码'MM / DD / YYYY HH:MM:SS')

The column where I save the date and time of the events that I'm registering

2)我用熊猫阅读这个“已存在的”工作表,一切都很顺利(即大熊猫可以阅读这些日期/时间):

import pandas as pd
df = pd.read_excel(myPath + 'myFile.xlsx',sheetname='pre-existent',header=0)

print(df['timeStampUTC'])

          timeStampUTC  
0  2018-12-02 12:59:00  
1  2018-12-02 14:29:00  
2  2018-12-02 15:39:00  
3  2018-12-02 17:05:00  
4  2018-12-02 18:38:00  
5  2018-12-02 19:36:00  
6  2018-12-02 20:27:00  
7  2018-12-02 21:44:00  
8  2018-12-02 22:15:00  
9  2018-12-02 22:46:00  
10 2018-12-02 23:07:00  
11 2018-12-04 15:46:00  
12 2018-12-04 15:53:00 
Name: timeStampUTC, dtype: datetime64[ns]

3)我做了一些计算并将这些其他计算存储在同一文件('myFile.xlsx')的新工作表中并保存更改:

from openpyxl import *

writer = pd.ExcelWriter(myPath + 'myFile.xlsx', engine = 'openpyxl')
writer.book = book
New_df.to_excel(writer, index = False, sheet_name='new-sheet')
writer.save()
writer.close()

4)一旦我尝试重复步骤2,大熊猫就无法再正确读取我的专栏中的日期时间:

print(df['timeStampUTC'])

          timeStampUTC 
0    NaN
1    NaN
2    NaN
3    NaN
4    NaN
5    NaN
6    NaN
7    NaN
8    NaN
9    NaN
10   NaN
11   NaN
12   NaN
Name: timeStampUTC, dtype: float64

重要的是要注意当我用Excel重新打开'myFile.xlsx'时,该列显示为正常。当我将列的数字格式重新设置为Date(格式代码'MM / DD / YYYY HH:MM:SS')时,pandas再次能够读取时间戳。

Anything that allows me to re-read this column with pandas is welcome.

谢谢!!!!

Juancho Gossn

python excel pandas openpyxl datetime-format
1个回答
1
投票

部分解决方案:

打开工作簿时使用只读。将输出保存到新的Excel文件。 workbook = openpyxl.load_workbook(filename ='name.xlsx',read_only = True)

我的问题:2个字体单元格变为1个字体单元格。

© www.soinside.com 2019 - 2024. All rights reserved.