【问题标题】:To add number format to xlxs file using python使用 python 将数字格式添加到 xlsx 文件
【发布时间】:2020-05-12 20:39:10
【问题描述】:

我在 abc.xlxs 中有如下数据

date,qty,price,profitprice,sellprice
20200501,11,900,,20

使用 python 我希望输出为:

data,qty,price,profitprice,sellprice
20200501,11.00,900.00,,20.00

有人可以帮忙吗?

如何读取每列的值并添加数字格式并保存到 xlxs 文件?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    基于this answerAkshit Khurana

    import pandas as pd
    
    df = pd.read_excel("initial.xlsx")
    
    writer = pd.ExcelWriter("formatted.xlsx", engine = "xlsxwriter")
    df.to_excel(writer, index=False, header=True)
    workbook  = writer.book
    worksheet = writer.sheets['Sheet1']
    format1 = workbook.add_format({'num_format': '0.00'})
    worksheet.set_column('C:E', None, format1)  # Adds formatting to columns C-E
    writer.save()
    

    我认为此处发布的其他两个答案不起作用,原因与询问 this question 的原因相同。

    【讨论】:

    • 不客气!然后确保接受它作为答案
    • 当我试图将这个修改后的 xlxs 文件保存到 csv 中时,数字格式就消失了。有什么帮助吗?
    • df = df.astype({'price': float, 'profitprice': float, 'sellprice': float}) 或其他 2 个答案的解决方案适用于 csv
    【解决方案2】:

    你可以在read_excel使用dtype参数:

    pd.read_excel('abc.xlxs', dtype={'profitprice': float, 'sellprice': float})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多