How does python open an xlsx and write data in list format

What is the bug in the following code self.fp = open(f'./{file_name}.xlsx', 'w', encoding='utf-8'), how does python open an xlsx and write data in list format

The problem with the following code is:

  • The 'w' parameter will open the file in write mode, but .xlsx workbook files are not text files, but a binary file format, so you should change their open mode to 'wb' (binary write mode) instead of 'w'.

The correct way is to use the module's methods to open, create and write Excel workbook files after importing openpyxlthe module , for example:

import openpyxl

# 创建一个工作簿对象
workbook = openpyxl.Workbook()

# 选定工作表(worksheet)对象
worksheet = workbook.active

# 写入数据
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in data:
    worksheet.append(row)

# 保存工作簿为 Excel 文件
file_name = "example"
workbook.save(f'{
      
      file_name}.xlsx')

Here we use the openpyxl library to open and create a workbook, select a worksheet, and then write data in the form of a list. wbmode will open the workbook in binary write mode, which is the correct way to open Excel files. After writing the data, use .save()the method to save the workbook as an Excel file.

Guess you like

Origin blog.csdn.net/weixin_45934622/article/details/130215447
Recommended