简体   繁体   English

使用to_csv将Excel文件转换为csv,即使将单元格格式化为字符串,也会删除前导零

[英]Converting Excel file to csv using to_csv, removes leading zeros even when cells are formatted to be string

When I try to convert my excel file to csv, using to_csv function, all my item number that has 1 leading 0, loses it except for the very first row. 当我尝试将我的excel文件转换为csv时,使用to_csv函数,我的所有项目编号都有1个前导0,除了第一行外,它都会丢失。

I have a simple forloop that iterates through all cells and converts cell values to string so I have no idea why only first row gets converted to csv format correctly with the leading 0. 我有一个简单的forloop迭代遍历所有单元格并将单元格值转换为字符串,所以我不知道为什么只有第一行正确地转换为csv格式与前导0。

for row in ws.iter_rows():
    for cell in row:
        cell.value = str(cell.value)

pd.read_excel('example.xlsx').to_csv('result.csv', index=False, line_terminator = ',\n')

eg https://i.stack.imgur.com/Njb3n.png (won't let me directly add image but it shows the following in excel) 例如https://i.stack.imgur.com/Njb3n.png (不会让我直接添加图片,但它在excel中显示以下内容)

0100,03/21/2019,4:00,6:00
0101,03/21/2019,4:00,6:00
0102,03/21/2019,4:00,8:00

turns into: 变成:

0100,03/21/2019,4:00,6:00,
101,03/21/2019,4:00,6:00,
102,03/21/2019,4:00,8:00,

What can I do to have 0 in front of all the first items in csv? 如果在csv中的所有第一项前面有0,我该怎么办?

Any insight would be appreciated. 任何见解将不胜感激。

So if you have not header in excel file: the name by default of columns is 0,1,... and so on 因此,如果excel文件中没有标题:默认情况下列的名称是0,1,......等等

if you want to keep the zero at column 0 for example, just do: 例如,如果你想将零保持在第0列,只需:

pd.read_excel('example.xlsx', header=None, dtype={0:str})\
  .to_csv('result.csv', index=False, line_terminator = ',\n'

if you havent header and you dont precise header=None, the first row is the header. 如果你没有标题,你不精确标题=无,第一行是标题。 dtype={0:str} indicates the column 0 will be str. dtype = {0:str}表示列0将是str。

be carefull when you save the excel file to csv, the header is saved (here with your options), the first row will be 0,1,.. (name of columns) 将excel文件保存到csv时要小心,保存标题(这里有你的选项),第一行将是0,1,..(列名)

if you dont want header to csv file use: 如果你不想要头文件到csv文件使用:

pd.read_excel('e:/test.xlsx', header=None, dtype={0:str})\
  .to_csv('e:/result.csv', index=False, header=False, line_terminator = ',\n')

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

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