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.
Article Directory
1. My needs
I want the last 1 column of excel to be converted from list form to numeric type
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
- 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
- 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))
- Pay attention to this number of rows, it needs to be incremented after processing a row