pandas 熊猫在excel编写器中设置单元格格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24493918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas set cell format in excel writer
提问by Felix
I am using pandas to read and write excel files with python (xlsx files, using openpyxl). Part of my data is text that looks like numbers. For instance, in the original excel file, I have a cell
我正在使用 Pandas 来读取和写入带有 python 的 excel 文件(xlsx 文件,使用 openpyxl)。我的部分数据是看起来像数字的文本。例如,在原始的 excel 文件中,我有一个单元格
123456789012345
123456789012345
and it imports fine as text in python. However, if I write the excel file again, the output cell has format 'General' and shows as
它在 python 中以文本形式导入。但是,如果我再次写入 excel 文件,输出单元格的格式为“常规”并显示为
1.23e14
1.23e14
So my question is: Is there any way to set the number format in pandas? I would like to set it to '@', i.e., to openpyxl.styles.NumberFormat.FORMAT_TEXT.
所以我的问题是:有没有办法在 Pandas 中设置数字格式?我想将其设置为“@”,即openpyxl.styles.NumberFormat.FORMAT_TEXT.
Unfortunately, the documentation of pandas.ExcelWriter is not so advanced (i.e., it does not exist).
不幸的是,pandas.ExcelWriter 的文档并不是那么先进(即它不存在)。
Thank you for your help.
感谢您的帮助。
回答by Happy001
I think in the worst case you can manipulate cells directly. I don't have Excel installed but maybe you can check if this works.
我认为在最坏的情况下,您可以直接操作单元格。我没有安装 Excel,但也许您可以检查这是否有效。
In [67]: df=pd.DataFrame ([123456789012345])
In [68]: writer = pd.ExcelWriter ('e.xlsx', engine='openpyxl')
In [69]: df.to_excel (writer, 'sheet1')
In [70]: ws = writer.sheets['sheet1']
In [71]: ws['A1'].style.number_format.format_code='@'
In [72]: writer.save ()
In [73]: pd.read_excel ('e.xlsx')
Out[73]:
0
0 123456789012345

