简体   繁体   English

Python Xlsx 书写格式建议

[英]Python Xlsx writing format advice

I've created a list and a for loop to iterate over each item in it to print it to a cell in excel.我创建了一个列表和一个 for 循环来迭代其中的每个项目以将其打印到 excel 中的单元格。 I'm using openpyxl.我正在使用 openpyxl。 When I first started using it using easy statements like:当我第一次开始使用它时,使用简单的语句,例如:

sheet["A1"] = "hello"

results in Cell A1 perfectly representing the hello value, without quotation marks.导致单元格 A1 完美地表示 hello 值,没有引号。

I have this code:我有这个代码:

workbook = Workbook()
sheet = workbook.active
text = ["Whistle", "Groot", "Numbers", "Mulan", "Buddy Holly"]
other = [5, 8, 100, 120]
for i in range(1,len(text)+1):
    cell_letter = "A"
    cell_number = str(i)
    sheet[str((cell_letter + cell_number))] = str(text[i-1:i])

and it writes to the corresponding cell locations with the iterations over the variable "text".并通过对变量“text”的迭代写入相应的单元格位置。 But when i open the file the format is ['Whistle'] and ['Groot']但是当我打开文件时,格式是 ['Whistle'] 和 ['Groot']

What am I missing?我错过了什么? Should I be passing each iteration to another variable to convert it from a list to a tuple for it to be written in then?我应该将每次迭代传递给另一个变量以将其从列表转换为元组以便写入吗?

Sorry if my code seems a bit messy, I've literally just learned this over the past few hours and it's (kind of) doing what I need it to do, with the exception of the writing format.对不起,如果我的代码看起来有点乱,我在过去几个小时里才真正学会了这一点,它(有点)做我需要它做的事情,除了写作格式。

Openpyxl let you write a list of lists, where the intern lists represents the 'lines' in a xlsx file. Openpyxl 允许您编写列表列表,其中实习生列表表示 xlsx 文件中的“行”。

So, you can store what you want as:因此,您可以将想要的内容存储为:

data_to_write = [["Whistle", "Groot", "Numbers", "Mulan", "Buddy Holly"]]

or, if you want some data in the next line:或者,如果您想在下一行中显示一些数据:

data_to_write = [["Whistle", "Groot", "Numbers"], ["Mulan", "Buddy Holly"]]

then, add it to your WorkSheet:然后,将其添加到您的工作表中:

for line in data_to_write:
    sheet.append(line)

and, finally, save it:最后,保存它:

workbook.save("filename.xlsx")

The full code could be something like:完整的代码可能类似于:

from openpyxl import Workbook

workbook = Workbook()
sheet = workbook.active

data_to_write = [["Whistle", "Groot", "Numbers", "Mulan", "Buddy Holly"]]

for line in data_to_write:
    sheet.append(line)

workbook.save('example.xlsx')

Give it a try and, then, give me a feedback, please XD试一试,然后给我反馈,请XD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM