Home Backend Development Python Tutorial How to automate excel in python

How to automate excel in python

Oct 20, 2020 am 09:45 AM
python

How to automate excel with python: first install the python toolkit; then read the excel table from the specified file path and perform certain operations; then save it to another excel file; and finally call the [excel_update] method.

How to automate excel in python

Related free learning recommendations: python video tutorial

How to automate excel with python:

1. Toolkit

1. xlrd: from Excel spreadsheet Extract data doc address: https://xlrd.readthedocs.io/en/latest/

2. xlwt: Write data into Excel spreadsheet doc address: https://xlwt.readthedocs.org/en /latest/

3. xlutils: Provides a set of utilities for processing Excel files. Doc address: https://xlutils.readthedocs.io/en/latest/

2. Installation

python -m pip install xlrd xlwt xlutils

3. Basic usage

The related toolkit for python operating excel can be detailed in Manipulate the fill style, value type, value size, etc. of the specified cell. However, Python requires certain pandas data processing skills to operate excel. A chapter will be added later: pandas data processing skills

1. Read the excel table from the specified file path, perform certain operations, and then save it to another excel file: result.xlsx

import xlwt
import xlrd
from xlutils.copy import copy
import pandas as pd
from pandas import DataFrame,Series
import os
os.chdir('./')
# 从指定文件路径读取excel表格
df = pd.read_excel('D:/mypaper/data/data.xlsx')
# 查看df内容
# 根据age算出出生年份,增加一列
import datetime
import os
year = datetime.datetime.now().year#获取当前系统时间对应的年份
df['birth'] = year-df['age']
df.to_excel('result.xlsx')#保存到当前工作目录,可以用os.getcwd()查看
#查看下此时df的内容,可以看到已经生成了birth这一列
Copy after login

At first glance, it seems that only pandas is used, and the three toolkits introduced above have not been used. Here is an introduction to using python to operate the underlying layer of excel

2. Cell operation

# 定义方法:读取指定目录下Excel文件某个sheet单元格的值
def excel_read(file_path,table,x,y):
     data = xlrd.open_workbook(file_path)
     table = data.sheet_by_name(table)
     return table.cell(y,x).value
# 定义方法:单元格值及样式
write_obj_list = []
def concat_obj(cols,rows,value):
    write_obj_list.append({'cols':cols,'rows':rows,'value':value,\
'style':xlwt.easyxf('font: name 宋体,height 280;alignment: horiz centre')})
# 定义方法:合并单元格
def merge_unit(srows,erows,scols,ecols,value):
    write_obj_list.append({'id':'merge','srows':srows,'erows':erows,'scols':scols,\
'ecols':ecols,'value':value,'style':xlwt.easyxf('font: name 宋体,height 280;alignment: horiz centre')})
# 定义方法:更新excel
excel_update(file_path,write_obj_list,new_path):
    old_excel = xlrd.open_workbook(file_path, formatting_info=True)
    #管道作用
    new_excel = copy(old_excel)
    '''
    通过get_sheet()获取的sheet有write()方法
    '''
    sheet1 = new_excel.get_sheet(0)
    '''
    1代表是修改第几个工作表里,从0开始算是第一个。此处修改第一个工作表
    '''
    for item in write_obj_list:
        if 'id' not in item.keys():
            if 'style' in item.keys():
                sheet1.write(item['rows'], item['cols'], item['value'],item['style'])
            else:
                sheet1.write(item['rows'], item['cols'], item['value'])
        else:
            if 'style' in item.keys():
                sheet1.write_merge(item['srows'],item['erows'],item['scols'], item['ecols'], item['value'],item['style'])
            else:
                sheet1.write_merge(item['srows'],item['erows'],item['scols'], item['ecols'], item['value'])
    '''
    如果报错 dict_items has no attributes sort
    把syle源码中--alist.sort() 修改为----> sorted(alist) 
    一共修改2次
    '''
    new_excel.save(file_path)
#参数详解
# srows:合并的起始行数
# erows:合并的结束行数
# scols:合并的起始列数
# ecols:合并的结束列数 
# value:合并单元格后的填充值
# style:合并后填充风格:
#     font: name 宋体
#     height 280;
#     alignment: horiz centre
#     ... 与excel操作基本保持一致
Copy after login

Note: This method only saves the actions that need to be performed directly into a list. The real action has not yet been executed. The execution action occurs in the excel_update method

Finally call the excel_update method and pass in the write_obj_list of the operations and fill values ​​required for each cell and the file saving path file_path

The desired Excel result file can be generated in the current working directory .

Note:

1.write_obj_list supports user customization

2.write_obj_list can also read existing excel files to be modified according to the excel_read method (can be maintained (original table format) and generate

There are many other basic methods for Python to operate excel. Due to space limitations, they will not be stated and demonstrated. Those who want to study in depth can click on the doc address above.

Learn python to operate excel cells and master the above methods, you can basically realize automated report operations in excel.

The above is the detailed content of How to automate excel in python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles