【问题标题】:Converting an excel tab to a CSV file is casting my columns into floats. Need to change to String将 excel 选项卡转换为 CSV 文件正在将我的列转换为浮点数。需要改成String
【发布时间】:2021-11-04 04:47:13
【问题描述】:

所以我一直在阅读openpyxlcsv 的文档,我似乎可以弄清楚这一点。我正在做的是使用 Excel 工作簿并将其中一个选项卡转换为 csv。然后,使用上述 CSV,执行一些 ETL。

我的问题是,在最终的 CSV 中,我有一列混合了数字和字符串。 我的问题是,在 excel 中它看起来不错,但在 notepad++ 中,您可以看到正在添加的浮点数。我需要将此列保留为字符串。

在我的 ETL 代码中,我已将此列转换为字符串,但所做的只是将浮点数从 excel 转换为 csv 转换,并将它们转换为字符串,但仍添加了 .0。

ETL 中转换为字符串的代码

df['Old Serial Number'] = df['Old Serial Number'].astype(str)#Old Serial Number is the column with a mix of strings and INT'S (see notepad++ image) 

是否可以在创建 CSV 时将列转换为字符串,以便删除浮点数?

这是我用于转换的代码。

import openpyxl
import csv
import glob
import datetime
import shutil
import time
import logging

def convert_to_csv():
for filename in glob.glob(
        r"C:\Users\excel_file_that_i_want*"):
    wb = openpyxl.load_workbook(filename)
    sh = wb['Report']#excel tab i want from the workbook

    with open('excel_file_that_i_want' + datetime.datetime.today().strftime('%d%m%Y%H%M%S''.csv'), 'w', encoding='utf-8',
              newline="") as f:
        col = csv.writer(f,
                         quotechar='"', quoting=csv.QUOTE_ALL)
        for row in sh.rows:
            col.writerow([cell.value for cell in row])
logging.info('Excel file converted to CSV')

【问题讨论】:

  • 为什么不转换成整数? CSV 中的所有值都是 always 字符串。
  • 这也可以,只要它摆脱了我的花车。我将如何在代码中做到这一点?

标签: python excel csv openpyxl


【解决方案1】:

这是因为 openpyxl 从其类型解释 Excel 单元格的值。

您可以通过以下方式快速 pypass:

col.writerow([str(cell.value) for cell in row])

【讨论】:

  • 这是有道理的,但是这个解决方案是否只适用于每个单元格而不是整个列?我正在处理相当多的数据,所以induvial cell 不起作用。
  • 使用以下建议的代码,CSV 返回为空白?
  • 你的python和openpyxl是哪个版本的?我不能用我的复制它。
  • Python 3.7 和我使用 openpyxl 3.0.7
  • 相同版本的 openpyxl。你能分享一个xlsx文件的例子吗?
猜你喜欢
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 2011-01-11
  • 2015-09-16
  • 2011-01-08
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
相关资源
最近更新 更多