简体   繁体   中英

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. I'm using 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.

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". But when i open the file the format is ['Whistle'] and ['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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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