【发布时间】:2016-04-23 20:56:47
【问题描述】:
我正在尝试使用 python 从字典列表中创建一个 excel 文件。最初我收到编码不当的错误。所以我将我的数据解码为“utf-8”格式。现在创建 excel 后,当我检查每个字段中的值时,它们的格式已更改为纯文本。以下是我在使用 sn-p 代码执行此活动时使用的 stpes。
1.>我在创建 excel 文件时遇到编码不正确的错误,因为我的数据中有一些 'ascii' 值。错误sn-p:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 16: ordinal not in range(128)
2.>为了消除编码不当的错误,我在读取输入 csv 文件时插入了一个 decode() 函数。解码为“utf-8”时的代码片段:
data = []
with open(datafile, "r") as f:
header = f.readline().split(',')
counter = 0
for line in f:
line = line.decode('utf-8')
fields = line.split(',')
entry = {}
for i,value in enumerate(fields):
entry[header[i].strip()] = value.strip()
data.append(entry)
counter += 1
return data
3.>插入 decode() 函数后,我使用以下代码创建了我的 excel 文件:
ordered_list= dicts[0].keys()
wb=Workbook("New File.xlsx")
ws=wb.add_worksheet("Unique")
first_row=0
for header in ordered_list:
col=ordered_list.index(header)
ws.write(first_row,col,header)
row=1
for trans in dicts:
for _key,_value in trans.items():
col=ordered_list.index(_key)
ws.write(row,col,_value)
row+=1 #enter the next row
wb.close()
但是在创建 excel 之后,excel 的每个字段中的所有值都是文本格式而不是它们的原始格式(一些日期时间值、十进制值等)。如何确保数据格式不会与我使用输入 csv 文件读取的输入数据格式发生变化?
【问题讨论】:
-
请将您失败的程序缩减为一个简短、完整的程序来演示错误。请完整发布该简短完整的程序,以及对您观察到的结果和您期望的结果的描述。请参阅How to Ask 和minimal reproducible example 了解更多信息。
-
@Robᵩ 我已经编辑并以结构化的方式提出了我的问题。如果您认为它仍然不清楚,请让我知道这个问题。我会尽量提供尽可能详细的信息。
-
Python 2.x 还是 Python 3.x?您使用的是哪个 Excel 库?打开pyxl?
-
@AlastairMcCormack 我正在使用 Python 2.x。最初我使用 Xlsxwriter 写入 excel 工作簿。然后,在将输入的 csv 文件转换为 xlsx 工作表后,我使用 Xlrd 库来读取和写入 excel。感谢您的帮助!
-
xlrd 适用于旧式 .xls,您的代码显示您正在从 CSV 读取数据。那你现在用的是哪一个?
标签: python excel dictionary utf-8 ascii