[英]Reading .txt file as list and writing list to 'single excel cell' using openpyxl
我正在從多行“.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:\Anaconda3\lib\site-packages\openpyxl\cell\cell.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))
Output:
['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'>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.