首页 > 解决方案 > 如何使用xlsxwrite python删除“单元格中的数字格式为文本”

问题描述

我正在研究 python 脚本,我将一些数据保存在 excel 表中。为此,我正在使用xlsxwriter. 我有以下代码:

out_xls_path = os.path.join(dir_path, 'moprime', 'output.xlsx')
workbook = xlsxwriter.Workbook(out_xls_path)
io_sheet = workbook.add_worksheet("Input-Output ()")

io_sheet.set_column(1, 3, 25)
style = workbook.add_format({'bold': True, 'font_name': 'Calibri', 'align': 'center', 'border': 1})
io_sheet.write('C1', "ch/sl spread", style)
io_sheet.write('D1', "{}%".format(chsl_spread), style)
io_sheet.write('C2', "ch/sl spread", style)
io_sheet.write('D2', 23, style)

做上面,下面是excel表:

在此处输入图像描述

我想了解D1如何删除它所说的那个小点The number in the cell is formatted as text。谢谢

标签: pythonexcelxlsxwriter

解决方案


要在 Excel 中创建百分比数字,您需要除以 100 并应用数字格式,例如“0.00%”。如果将其格式化为字符串,您将收到您看到的警告。

这是一个基于您的工作示例:


import xlsxwriter

out_xls_path = 'output.xlsx'
workbook = xlsxwriter.Workbook(out_xls_path)
io_sheet = workbook.add_worksheet("Input-Output ()")

io_sheet.set_column(1, 3, 25)

style = workbook.add_format({'bold': True,
                             'font_name': 'Calibri',
                             'align':
                             'center', 'border': 1})

percent = workbook.add_format({'bold': True,
                               'font_name': 'Calibri',
                               'align':
                               'center', 'border': 1,
                               'num_format': '0.00%'})

chsl_spread = 29.82

io_sheet.write('C1', "ch/sl spread", style)
io_sheet.write('D1', chsl_spread / 100.0, percent)
io_sheet.write('C2', "ch/sl spread", style)
io_sheet.write('D2', 23, style)

workbook.close()

输出

在此处输入图像描述


推荐阅读