Openpyxl number_format not modifying cell values derived from formula
Openpyxl的'number_format'不会修改从公式得出的单元格值,因为结果值是Python中的String类型。
对于读取轨迹信息的软件,我需要采用特定的自定义格式的数据。
注意:我已经看到了此处解决的相同问题:https://bitbucket.org/openpyxl/openpyxl/issues/376/number-format-not-refreshing-cells
I agree with the original answer: the issue is that excel is not storing the data resulting from the formulas in its cache. The data is stored as a string. I am just not sure how to change the data from String to int once it is read by Openpyxl:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import csv import openpyxl from openpyxl.styles import Alignment wb = openpyxl.Workbook() ws = wb.active wb.active f = open(r"...\\....\\...\\automated.csv") reader = csv.reader(f, delimiter=',') for row in reader: ws.append(row) f.close() wb.save(r"...\\...\\...\\...\\automated.xlsx") sheet=wb.active wb.guess_types = True sheet['F1'] = '***** Time Start' rowNumber = 2 # Start reading from row 3 for i, cellObj in enumerate(ws, 3): # 3 is the starting row to write on rowNumber += 1 cellObj = ws.cell(row=i, column=6) # 6 is the column to start writing on cellObj.value = '=OFFSET(B6,E{0},0)'.format(str(rowNumber).format(i)) cellObj.number_format = 'dd mmm yyyy hh:mm:ss.000"UTCG"' if i == 25: break ws = wb.active wb.save(r"...\\...\\...\\...\\automated.xlsx") |
我知道代码正在工作,因为存储为'0'的值已被代码完美修改(请参见突出显示),因为它们不对该单元格使用任何公式:
注意:number_format应用于所有单元格(我检查了每一行):
但是由于单元格是字符串,所以它不能反映更改。
I am fairly new to Python and attempted to cast
cellObj.value as an int but that did not work.blockquote>
任何帮助或建议如何做到这一点将不胜感激。在过去的4天里,我一直在研究Stack Overflow,但没有看到解决此问题的任何方法。谢谢!
编辑:我正在使用最新版本的openpyxl 2.5.3,并尝试过此操作:
openpyxl python-将csv写入excel可以将数字设置为文本格式,但无法正常工作-我所有的值都变成了零:
![]()
您将需要使用
strptime 方法将字符串转换为datetime对象。