用python将txt文档写入excel,并将文本类型装成数字类型

我把txt文档中的数据导入excel后无法识别成数字,怎么转换呢;代码如下:
import xlsxwriter
workbook = xlsxwriter.Workbook("chart.xlsx")
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type':'column'})
title = ['业务名称','星期一','星期二','星期三','星期四','星期五','星期六','星期日','平均流量']
buname = ['业务官网','新闻中心','购物频道','体育频道','亲子频道']

format = workbook.add_format()
format.set_num_format('0.0')

format_title = workbook.add_format()
format_title.set_border(1)
format_title.set_bg_color('#cccccc')

format_title.set_align('center')
format_title.set_bold()

format_ave = workbook.add_format()
format_ave.set_border(1)
#format_ave.set_num_format('0.00')

worksheet.write_row('A1',title,format_title)
worksheet.write_column('A2',buname,format)

with open('number.txt') as file:
data = file.readlines()
worksheet.write_row('B2',data[0:7])
worksheet.write_row('B3',data[7:14],format)
worksheet.write_row('B4',data[14:21],format)
worksheet.write_row('B5',data[21:28],format)
worksheet.write_row('B6',data[28:35],format)

def chart_series(cur_row):
worksheet.write_formula('I'+cur_row,'=SUM(B'+cur_row+':H'+cur_row+')',format_ave)
chart.add_series({
'categories': '=Sheet1!$b$1:$H$1',
'values':'=Sheet1!$b$'+cur_row+':$H$'+cur_row,
'line': {'color':'black'},
'name': '=Sheet1!$A$'+cur_row,
})
for row in range(2,7):
chart_series(str(row))
chart.set_size({'width':577,'height':287})
chart.set_title({'name':'业务流量周报报表'})
chart.set_y_axis({'name':"Mb/s"})

worksheet.insert_chart('A8',chart)
workbook.close()

1个回答

Excel数据写入的时候使用worksheet.write_number(),将从txt读取的数据转为数字,逐个单元格进行写入。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问