python 在使用 xlsxwriter组件写入数据时,当数据包含类似“http://*** /”数据时,导出的excel,打开时会提示如下错误:
没有查到相关的资料处理这个问题,可能原因为excel识别为链接,与内置库冲突导致,对数据准确性无大影响的情况下,只能临时通过字符替换解决:
if keyword.startswith('http://') and keyword.find(' ') >= 0:
keyword = keyword.replace('','')
截取的部分代码如下:
os.chdir('/data/scripts/file/')
filename = "统计-" + last_month + ".xlsx" # 将查询的结果写入至EXCEL
workbook = xlsxwriter.Workbook(filename)
worksheet = workbook.add_worksheet(name="数据统计")
worksheet.set_column("B:B", 40)
#header_style = workbook.add_format({})
header_style = workbook.add_format({"bold" : True, "font_size" : 10, "align" : "center", "bg_color" : "#DCDCDC", "top" : 1, "bottom" : 1, "left" : 1, "right" : 1})
#item_style = workbook.add_format({})
item_style = workbook.add_format({"font_size" : 10, "align" : "center", "top" : 1, "bottom" : 1, "left" : 1, "right" : 1}) # 写入表头
worksheet.write(0,0,"序号",header_style)
worksheet.write(0,1,"词",header_style)
worksheet.write(0,2,"总数",header_style)
sorted_search_dict = sorted(search_dict.items(), key=lambda d:d[1], reverse = True)
# 写入数据项
data_row = 0
for i in sorted_search_dict:
data_row += 1
keyword = i[0].strip()
if keyword.startswith('http://'):
keyword = keyword.replace('','')
#print(str(data_row) + "," + i[0] + "," + str(i[1]))
worksheet.write(data_row , 0, data_row, item_style)
worksheet.write(data_row , 1, keyword, item_style)
worksheet.write(data_row , 2, i[1], item_style)
workbook.close()