[Python] Use python to process excel table data

Python has many libraries that can be used to process Excel tabular data, the most commonly used of which are pandasand openpyxl.

  1. pandas library

The pandas library is a very powerful Python library for data analysis and manipulation. It supports processing various data types, including Excel table data.

First you need to install the pandas library. You can install the pandas library in the terminal or command prompt with the following command:

pip install pandas

The data from the Excel file can then be read into a pandas DataFrame using the following code:

import pandas as pd

# 读取Excel文件
df = pd.read_excel('data.xlsx')

# 打印DataFrame
print(df)

The print result is as shown below:
Insert image description here

If you want to write a pandas DataFrame into an Excel file, you can use the following code:

# 将DataFrame数据写入Excel文件
df.to_excel('datasave.xlsx', index=False)

The resaved information is as shown in the figure:

Insert image description here

  1. openpyxl library

The openpyxl library is a Python library specifically designed for processing Excel files. It provides many functions for reading and writing Excel files, including reading and writing data, styles, charts, etc.

First, you need to install the openpyxl library. You can install the openpyxl library in the terminal or command prompt through the following command:

pip install openpyxl

The data from the Excel file can then be read into openpyxl's Workbook object using the following code:

import openpyxl

# 打开Excel文件
workbook = openpyxl.load_workbook('data.xlsx')

# 选择工作表
worksheet = workbook.active

# 遍历行和列,打印单元格数据
for row in worksheet.iter_rows():
    for cell in row:
        print(cell.value)

Insert image description here

If you want to write data into an Excel file, you can use the following code:

import openpyxl

# 创建一个新的Excel文件
workbook = openpyxl.Workbook()

# 创建一个新的工作表
worksheet = workbook.active

# 写入数据
worksheet['A1'] = 'Hello'
worksheet['B1'] = 'World'

# 保存Excel文件
workbook.save('datawrite.xlsx')

Open the excel table and you can see that the information is written successfully.

Insert image description here

The above are common methods for using Python to process Excel table data, which can be adjusted according to specific needs.

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/132615255