If I want to write a weekly report in Python (Python uses Pandas to read and write Excel)

Begin with two sentences BB

Basically, the weekly report written every Friday is this routine.

clipboard2.png

Suddenly I want to use Python to work intelligently and modify Excel tables.

Forget about the operations of merging cells and modifying table styles. Just do a simple read and write first.

Operation process

Install Python

If you want to do good things, you must first sharpen your tools. First of all, do the preparation work, and the development environment is essential.

Download the installation package directly from the official website, I am using version 3.6.5. After downloading and installing, configure the environment variables.

For development tools, I used vscode directly and installed a python plugin.

Press and hold ctl + alt + P to set the Python selection interpreter.

clipboard.png

Pandas official website address

pandas.pydata.org/

Pandas Chinese Documentation

www.pypandas.cn/

Pandas installation package

Pandas processing Excel requires xlrd, openpyxl dependencies

pip install pandas
pip install xlrd
pip install openpyxl
复制代码

Get started

As shown on the official website, the use method is as simple as 1, 2, 3

# 1、安装包
$ pip install pandas

# 2、进入python的交互式界面
$ python -i

# 3、使用Pandas
>>> import pandas as pd
>>> df = pd.DataFrame() 
>>> print(df)

# 4、输出结果
Empty DataFrame
Columns: []
Index: []
复制代码

Create Excel, write data

import  pandas  as pd
from pandas import DataFrame

#创建DataFrame可以用下面字典,也可以用数组ndarray
dic = {'标题列1': ['malena','morgan'],
        '标题列2': [36, 34]
       }
df = pd.DataFrame(dic)
df.to_excel('write_test.xlsx', index=False)
复制代码

Execute the py file and write it successfully, it feels very nice.

clipboard1.png

Introducing pandas DataFrame objects

import pandas as pd
from pandas import DataFrame
复制代码

Write to Excel file, official example:

df.to_excel('foo.xlsx', sheet_name='Sheet1')
复制代码

Read Excel file, official example:

 pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA'])
复制代码

There is a small hole here:

The reason is that xlrd has recently been updated to version 2.0.1, which only supports .xls files. So pandas.read_excel('xxx.xlsx') will report an error.

You can install an older version of xlrd and run in cmd:

pip uninstall xlrd
pip install xlrd==1.2.0
复制代码

It is also possible to open .xlsx files with openpyxl instead of xlrd:

df=pandas.read_excel(‘data.xlsx’,engine=‘openpyxl’)
复制代码

Read Excel file and print it

data = pd.read_excel('zmy-weekly.xlsx', sheet_name='3月', engine='openpyxl')
print(data)
复制代码

The print result is as shown below:

clipboard3.png

Change the data by modifying the value of data.loc. data.loc can be roughly understood as a two-dimensional array, corresponding to the cells of each row and each column.

For example, modify "work item 2" to "work item 5", the corresponding single number cell, row 2, column 2

 data.loc[3][2] = '工作事项5';
复制代码

The modification is completed, and finally a new Excel sheet is written. You can set sheet_name, for example, set it to "March".

 DataFrame(data).to_excel('new.xlsx', sheet_name='3月', index=False, header=True)
复制代码

The complete code is as follows:

import pandas as pd
from pandas import DataFrame

# 3.8.2 pandas读写Excel
def write_weekly():
    data = pd.read_excel('zmy-weekly.xlsx', sheet_name='3月', engine='openpyxl')
    print(data)

    print(data.loc)

    data.loc[2][0] = '3月5周';
    data.loc[2][2] = '工作事项4';
    data.loc[3][2] = '工作事项5';
    data.loc[4][2] = '工作事项6';

    data.loc[2][4] = '已完成';
    data.loc[3][4] = '已完成';
    data.loc[4][4] = '已完成';

    data.loc[5][2] = '又是一个临时工作';


    data.loc[6][0] = '4月1周';

    data.loc[6][2] = '工作事项7';
    data.loc[7][2] = '工作事项8';

    data.loc[6][4] = '进行中';
    data.loc[7][4] = '进行中';

    # # 保存数据
    DataFrame(data).to_excel('new.xlsx', sheet_name='3月', index=False, header=True)


write_weekly();
复制代码

clipboard5.png

The styles are different, but it's not a big problem. Open last week's weekly report, select all, then format, click on the new weekly report, aha.

clipboard6.png

self-talk

In other words, Excel has already been opened, why not just change it faster?

However, after tossing around for a while, I should have made it clear about the basic operations of reading and writing Excel with Pandas through Python. I will toss again from time to time in the future.

Guess you like

Origin juejin.im/post/7080431880301969444