Home  >  Article  >  Backend Development  >  How to automate excel in python

How to automate excel in python

coldplay.xixi
coldplay.xixiOriginal
2020-10-20 09:45:2314790browse

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