First of all, there are many libraries for python to read Excel, including xlwings, pandas, xlrd, etc. I usually use openpyxl and pandas. Of course, I also like to convert Excel with a relatively large amount of data into csv format for reading.
Today we use openpyxl to read excel files. When reading, we can convert the information of each row into a list. Most importantly, we can output the row number of each row, so that the content of the cell can be modified later, and we can rely on line number
If I am in column K, add a column to fill in the line number of the above code
worksheet["K{line number}"] = assignment
Haha, I forgot to skip the first line (add a continue), but it doesn’t matter, the line number of the data is filled correctly (the code below is correct)
import os
import openpyxl
# 打开 Excel 文件,获取 Workbook 对象
workbook = openpyxl.load_workbook('./数据源/'+os.listdir('./数据源/')[0])# 选择需要读取数据的 Sheet,获取 Worksheet 对象
worksheet = workbook.active
# 循环遍历每一行,将每一行的数据以列表形式添加到 rows 列表中for i, row inenumerate(worksheet.iter_rows(values_only=True),1):if i==1:continue
d =list(row)
worksheet[f"K{
i}"]= i
print(f"行{
i}",d)
workbook.save("./结果.xlsx")
Set cell width, height, and background color
Let's make column B wider
worksheet.column_dimensions['B'].width = 15
worksheet.column_dimensions['1'].height = 15# This is the row height of the first row, and so on
Set cell background color
worksheet[’A1'].fill = PatternFill("solid", fgColor="3CB371")# For example, set cell A1 to the color ["3CB371"], which is a hexadecimal color
the code
import os
import openpyxl
from openpyxl.styles import PatternFill
# 打开 Excel 文件,获取 Workbook 对象
workbook = openpyxl.load_workbook('./数据源/'+os.listdir('./数据源/')[0])# 选择需要读取数据的 Sheet,获取 Worksheet 对象
worksheet = workbook.active
worksheet.column_dimensions['C'].width =20# 循环遍历每一行,将每一行的数据以列表形式添加到 rows 列表中
d2 ={
i:chr(i+64)for i inrange(1,27)}# print(d)for i, row inenumerate(worksheet.iter_rows(values_only=True),1):
k = i
if k<=11:
worksheet[d2[k]+'1'].fill = PatternFill("solid", fgColor="3CB371")if i==1:continue
d =list(row)
worksheet[f"K{
i}"]= i
print(f"行{
i}",d)
workbook.save("./结果.xlsx")
I hope everyone has to help
A little programmer dedicated to office automation
I've seen this, follow + like + bookmark = don't get lost! !
If you want to know more about Python office automation, please pay attention!