简体   繁体   中英

Adding array into excel using openpyxl (formatting issue)

I am using "openpyxl" to put an array into an excel file for users to download on a django site.

The data goes into the excel fine using the following loop:

for row_num, row in enumerate(matrix, 3):
 for col_num, item in enumerate(row, col_start - 12):
        ws.cell(column=col_num, row=row_num, value=item)
wb.save(excel_file_path_from_db)

My problem is that when the data enters the excel is is not in number format. I think it could be because i am getting my atix values from a user input via:

matrix = ast.literal_eval(list(request.GET)[0])
print(matrix)

Any ideas how I can make my matrix come into the excel file in number format?

Sounds like you have string values. The cell() function will set the data_type property of the resulting openpyxl.cell.cell.Cell object to try and match that.

If you assign the output of cell() to a variable (cell, for example): cell = ws.cell(column=col_num, row=row_num, value=item)

And then print(cell.data_type) , you will likely get "t" for text.

You should be able to use a cast operator on item when you invoke ws.cell():

for row_num, row in enumerate(matrix, 3):
 for col_num, item in enumerate(row, col_start - 12):
    ws.cell(column=col_num, row=row_num, value=float(item))
wb.save(excel_file_path_from_db)

Another option that worked for me:

for row_num, row in enumerate(matrix, 3):
 for col_num, item in enumerate(row, col_start - 12):
    cell = ws.cell(column=col_num, row=row_num, value=item)
    cell.data_type = "n"
wb.save(excel_file_path_from_db)

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