【问题标题】:Python XLSB to CSV conversion data typesPython XLSB 到 CSV 转换数据类型
【发布时间】:2019-04-13 00:10:13
【问题描述】:

我一直致力于创建一个脚本,将 Excel 文件转换为 csv,以便在我们的某些工具中进行进一步处理。

对于 xls、xlsx 和 xlsm,我找到了将文件作为文本对象打开或使用 pandas 的解决方案。当遇到 xlsb 文件时,我登陆了 pyxlsb 包,它可以工作...参考这里使用的代码How can I convert a XLSB file to csv using python?

遗憾的是,我注意到 xlsb 文件中的 int() 值似乎被转换为浮点数,因此作为浮点数写入我的 csv 文件。这显然是不可取的。

基本上我正在寻找一个 dtype=object 类型的解决方案。我想也许我可以添加一个使用另一个函数将值转换回 int 的步骤。但是我认为这效率低下并且容易出错。

我在 pyxlsb 页面 (https://pypi.org/project/pyxlsb/) 上环顾四周,但运气不佳。

我的代码:

    to_replace_list = ['\r', '\n', '\\r\\n', '\\' + str(out_del)]  # values to replace in all rows
    with open_xlsb(file_to_convert) as wb:  # open xlsb file using pyxlsb package
        for sheet_name in wb.sheets:  # loop over all sheets in file
            with wb.get_sheet(sheet_name) as sheet:  # open xlsb sheet obj
                out_file = out_filer(total_filename, sheet_name)  # define output file name based on source and sheet
                with open(out_file, 'a') as o:  # open output csv obj
                    for row in sheet.rows():  # loop over rows in xlsb obj
                        print([re.sub(value, '', str(cell.v)) for value in to_replace_list for cell in row])

sidequest:xlsb 文件中的空值在输出中将被称为 None。我希望这是''。

【问题讨论】:

    标签: python excel csv xlsb


    【解决方案1】:

    自 Pandas 1.0.1 发布以来,read_excel() 现在支持 xlsb

    pd.read_excel('path_to_file.xlsb', engine='pyxlsb')
    

    https://pandas.pydata.org/docs/user_guide/io.html#io-xlsb

    【讨论】:

      猜你喜欢
      • 2022-11-20
      • 1970-01-01
      • 2014-08-01
      • 2014-04-17
      • 2018-01-26
      • 2017-05-15
      • 2018-01-04
      • 2020-10-20
      • 1970-01-01
      相关资源
      最近更新 更多