An article takes you to use Python to do the reading, writing and processing of Excel tables (processing of xlsx files)

I have already written an article about Python's handling of excel files . If you need it, you can refer to it. This article is mainly to record some problems during my actual operation.

1. My needs

I want the last 1 column of excel to be converted from list form to numeric type

Insert picture description here
You can see that some of the last column is a list, and some are directly numeric.I want the entire list to be converted to numeric types

Second, the code

import openpyxl

def write_excel_xlsx():
    # 写入数据准备
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet.title = "优化后的参数"
    # 记录写的行数
    write_row = 0
    # 首先从excel中读取数据
    work_read = openpyxl.load_workbook("样本优化.xlsx")
    sheet_read = work_read["优化后的参数"]
    # 将表中的所有行转换为列表
    rows_data = list(sheet_read.rows)
    # 逐行读取
    for row in rows_data:
        for i in range(len(row)):
            value = row[i].value
            if isinstance(value, str):
                sheet.cell(row=write_row + 1, column=i + 1, value=str(value[1:len(value) - 1]))
            else:
                sheet.cell(row=write_row + 1, column=i + 1, value=str(value))
        write_row = write_row + 1
    workbook.save("样本优化-处理.xlsx")
    print("xlsx格式表格写入数据成功!")

write_excel_xlsx()

Three, summary

  1. Convert all rows in the table to a list
# 将表中的所有行转换为列表
rows_data = list(sheet_read.rows)

This step is very important, because we will operate on the specific number of columns later, so that the conversion is more convenient

  1. That list is in the form of a string in excel, so it needs to be judged separately
if isinstance(value, str):
   sheet.cell(row=write_row + 1, column=i + 1, value=str(value[1:len(value) - 1]))
else:
   sheet.cell(row=write_row + 1, column=i + 1, value=str(value))
  1. Pay attention to this number of rows, it needs to be incremented after processing a row

Guess you like

Origin blog.csdn.net/nanhuaibeian/article/details/108723903