我正在从多行'.txt'文件中读取数据,并在读取时将其转换为列表,并尝试使用以下代码将列表写入excel表的'单个单元格':
from openpyxl import load_workbook
with open('Wavedata.txt') as f:
lines = [line.rstrip() for line in f]
print(lines)
wb = load_workbook("Wavesheet.xlsx")
sheet = wb["Sheet1"]
sheet['A1'] = lines
wb.save("Wavesheet.xlsx")
列表生成成功如下:("123.23"、"145.43"、"156.29"、"145.16"、"150.23"、"154.21"、"155.31"、"155.29"、"155.64"、"155.32"、"154.69"、"151.65"、"150.89"、"146.87"、"145.52"、"124.32")
但是sheet['A1'] = lines
部分代码不工作,产生错误:
File "C:Anaconda3libsite-packagesopenpyxlcellcell.py", line 205, in _bind_value
raise ValueError("Cannot convert {0!r} to Excel".format(value))
ValueError: Cannot convert ['123.23', '145.43', '156.29', '145.16', '150.23', '154.21', '155.31', '155.29', '155.64', '155.32', '154.69', '151.65', '150.89', '146.87', '145.52', '124.32'] to Excel
有没有人建议我如何将列表写入Excel工作表的"单个单元格",包括列表开头的"["和末尾的"]"?关于
你可以把列表转换成字符串。
outputlist = ['123.23', '145.43', '156.29', '145.16', '150.23', '154.21', '155.31', '155.29', '155.64', '155.32', '154.69', '151.65', '150.89', '146.87', '145.52', '124.32']
outputstring ="['" + '', ''.join(outputlist) + "']"
print(outputlist, type(outputlist))
print(outputstring, type(outputstring))
输出:['123.23', '145.43', '156.29', '145.16', '150.23', '154.21', '155.31', '155.29', '155.64', '155.32', '154.69', '151.65', '150.89', '146.87', '145.52', '124.32'] <class 'list'>
['123.23', '145.43', '156.29', '145.16', '150.23', '154.21', '155.31', '155.29', '155.64', '155.32', '154.69', '151.65', '150.89', '146.87', '145.52', '124.32'] <class 'str'>