The most complete Python operation excel code, allowing you to get off work two hours earlier every day

In the digital age, many people often work with excel. This article introduces Python scripts to operate excel, making your work more efficient.
  

  

1. Install the openpyxl module

  
Python operation excel mainly uses the openpyxl module, press win+R to open cmd, enter in it

pip3 install openpyxl

The openpyxl module can be successfully installed.

  
  

2. Load the library

  
Then load the library and set the folder where the data is stored.

import os
import random
import openpyxl
import numpy as np
import pandas as pd
from openpyxl.drawing.image import Image
from openpyxl.worksheet.table import Table,TableStyleInfo
from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment
from openpyxl.utils import get_column_letter,column_index_from_string
#导入库

os.chdir(r'G:/python/13_python处理excel/')
#设置文件存放的地址

  
  

3. Create files and worksheets

  
Then create the file and worksheet, the code is as follows:

wb = openpyxl.Workbook()
#创建工作表
wb_sht1 = wb.create_sheet(title='插入数据', index=0)
wb_sht2 = wb.create_sheet(title='插入表格', index=0)
wb.save('cs.xlsx')
wb.close()

got the answer:
  
insert image description here

You can also use the function to delete the worksheet, the code is as follows:

wb.remove(wb_sht1)

  
  

4. Write data in the specified cell of the worksheet

  
Then write the data in the worksheet, the code is as follows:

#在每一行写入行号
wb = openpyxl.Workbook()
#创建工作表
wb_sht1 = wb.create_sheet(title='插入数据', index=0)
wb_sht2 = wb.create_sheet(title='插入表格', index=0)
for r_index in range(1, 10):
    for c_index in range(1, 10):
        wb_sht1.cell(row=r_index, column=c_index, value=r_index)

The two-layer for loop control writes down the line number at the corresponding position, and the result is obtained:
  
insert image description here

  
  

5. Set the color and font of the cell

  
Then set the font size, color, and border line in the A1 cell test, the code is as follows:

thin = Side(border_style="thin", color="FF0000")
#红色细线条
double = Side(border_style="double", color="000000")
#黑色粗线条
wb_sht1_A1 = wb_sht1["A1"]
#选择要调整颜色的单元格
wb_sht1_A1.font = Font(b=True, color='008000')
#设置单元格字体颜色
wb_sht1_A1.alignment = Alignment(horizontal='left', vertical='center')
#设置单元格排列方式
wb_sht1_A1.border = Border(top=double, left=thin, right=thin, bottom=double)
#设置边框线条
wb_sht1_A1.fill = PatternFill("solid", fgColor="0000FF")
#设置单元格填充颜色

got the answer:
  
insert image description here

  
  

6. Write the table in excel

  
Finally, write the table in excel, the code is as follows:

os.chdir(r'G:/python/13_python处理excel/')
#设置文件存放的地址
wb = openpyxl.Workbook()
#创建工作表
wb_sht1 = wb.create_sheet(title='插入数据', index=0)
wb_sht2 = wb.create_sheet(title='插入表格', index=0)
date = pd.DataFrame(np.random.randint(20, 50, (4, 4)))
col_name = ['col1', 'col2', 'col3', 'col4']
date.columns = col_name
wb_sht2.append(col_name)
for row in range(date.shape[0]):
    wb_sht2.append(list(date.iloc[row, ]))
table = Table(id=1, displayName='excel_table3', ref='A1:D4')
wb_sht2.add_table(table)
wb.save('cs1.xlsx')
wb.close()

got the answer:
  
insert image description here

So far, using the openpyxl module in Python to operate the excel code has been explained. Interested partners can test these codes in more depth. This article only gives the basic code, and more special requirements can be adjusted on the basis of this code. If you want to set the format in excel and only paste the data into the document, you can also call the xlwings module to perform excel operations.
  
If you want to know more about data analysis in Python, you can read related articles on the "Data Analysis" module in the "Ali Yiyang's Code" official account.

  
You may be interested in:
Draw Pikachu with Python Draw a
word cloud map
with Python Draw 520 eternal heartbeats with
Python With sound and text) Use the py2neo library in Python to operate neo4j and build a relationship map Python romantic confession source code collection (love, rose, photo wall, confession under the stars)



Guess you like

Origin blog.csdn.net/qq_32532663/article/details/127949846