简体   繁体   English

Django在Excel中进出口数值的前导零

[英]Django import-export leading zeros for numerical values in excel

I am faced with the following problem: when I generate .csv files in python using django-import-export even though the field is a string, when I open it in Excel the leading zeros are omitted. 我面临以下问题:当我使用django-import-export在python中生成.csv文件时,即使该字段是一个字符串,当我在Excel中打开它时,也会省略前导零。 Eg 000123 > 123. 例如000123> 123。

This is a problem, because if I'd like to display a zipcode I need the zeros the way they are. 这是一个问题,因为如果我想显示一个邮政编码,则需要按原样使用零。 I can cover it in quotes, but that's not desirable since it will grab unnecessary attention and it just looks bad. 我可以用引号将其覆盖,但这不是可取的,因为它会引起不必要的注意,并且看起来很糟糕。 I'm also aware that you can do it in Excel files manually by changing the data type, but I don't want to explain that to people who are using my software. 我也知道您可以通过更改数据类型在Excel文件中手动进行操作,但是我不想向正在使用我的软件的人解释这一点。

Any suggestions? 有什么建议么?

Thanks in advance. 提前致谢。

An easy fix would be adding an apostrophe (') at the beginning of each number when doing using import-export. 一个简单的解决方法是在使用import-export时,在每个数字的开头添加一个撇号(')。 This way Excel will recognize those numbers as a text. 这样,Excel会将这些数字识别为文本。

I've tried this solution. 我已经尝试过这种解决方案。 It's the solution suggested by @jquijano but it hasn't worked. 这是@jquijano建议的解决方案,但没有用。

After generating the CSV, I opened it with 'open office' and 'excel' and in both cases I could see the (') character at the beginning of each string. 生成CSV之后,我用“ open office”和“ excel”打开了它,在两种情况下,我都可以在每个字符串的开头看到(')字符。 However, if I added a new value to the CSV in the editor, for example '0895, the (') disappeared and the leading 0 wasn't removed. 但是,如果我在编辑器中将新值添加到CSV中,例如'0895,则(')消失,并且前导0未被删除。

Luckily, I found a workaround. 幸运的是,我找到了一种解决方法。 I just added an empty character at the beginning. 我只是在开头添加了一个空字符。

value = chr(24) + unidecode('00123')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM