search
HomeBackend DevelopmentPython TutorialHow 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这一列

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操作基本保持一致

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
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
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools