在选择字段上使用xlsxwriter strings_to_numbers选项

时间:2018-07-17 13:36:37

标签: python xlsxwriter

对于将数据导出到Excel的python应用程序,我具有以下代码。我希望将strings_to_numbers选项应用于一些字段,以使数字字段不会导出为“数字存储为文本”,但是,我不想将此选项应用于所有字段,因为我确实想保留某些字段作为文本,其中混合了字符值和带有前导零的值。

有没有办法选择性地应用strings_to_numbers选项?

nexusexp_file_name = "dataexport.xlsx"
workbook = xlsxwriter.Workbook(nexusexp_file_name,{'strings_to_numbers': True})
worksheet1 = workbook.add_worksheet('Sheet1')
textformat = workbook.add_format()
textformat.set_num_format('0')

cur.execute(query)
i = 2
for row in cur.fetchall():
    worksheet1.write('A' + str(i), row[0],textformat)
    worksheet1.write('B' + str(i), row[1])
    worksheet1.write('C' + str(i), row[2])
    worksheet1.write('D' + str(i), row[3])
    worksheet1.write('E' + str(i), row[4])
    worksheet1.write('F' + str(i), row[5])
    worksheet1.write('G' + str(i), row[6])
    worksheet1.write('H' + str(i), row[7])
    worksheet1.write('I' + str(i), row[8])
    worksheet1.write('J' + str(i), row[9],textformat)
    worksheet1.write('K' + str(i), row[10],textformat)
    worksheet1.write('L' + str(i), row[11])
    i += 1

1 个答案:

答案 0 :(得分:0)

如果所有数字都包含相同的数字,则非常简单。在代码中设置格式时,您处于正确的轨道。只需稍作调整即可。我在下面提供了一个完全可复制的示例,该示例说明了如何保留前导零。请注意,所有这些字符串都有七个字符,如果您有多个长度,则每种长度都需要使用不同的方法或格式。

import xlsxwriter

data = ('0010999', '2345678', '0123456', '1234567')

workbook = xlsxwriter.Workbook('test.xlsx',{'strings_to_numbers': True})
worksheet1 = workbook.add_worksheet('Sheet1')
textformat = workbook.add_format()
textformat.set_num_format('0000000')

worksheet1.write('A1', 'No Format')
worksheet1.write('B1', 'With Format')
worksheet1.write_column(1, 0, data)
worksheet1.write_column(1, 1, data, textformat)
workbook.close()

具有预期的输出:

Expected Output