Three ways for python to generate excel files

4017ac8006fcea251e621f01a8d69f04.png

(Forever free, scan code to join)

Reposted from: Python column

In our daily work, we will encounter the operation of excel, so today I will write an article on how to operate excel through python. Of course, there are many libraries for python to operate excel, such as pandas, xlwt/xlrd, openpyxl, etc. Each library has different differences. Let’s take a look at the specific differences~

057910ecba70c4294dd7bc7e3b936a9b.png

 xlwt/xlrd

  • xlrd is for reading Excel, and xlrd operates excel in xls/xlxs format

  • xlwt reads Excel, and xlwt operates excel in xls format

Install

xlrd is a third-party library of python, which needs to be installed through pip

pip install xlrd

1. Import the xlrd module

2. Open Excel to complete the instantiation

3. Obtain the corresponding table through the subscript (you can obtain it through the table name)

4. Get the data of the table by column, row or coordinate

Install

xlwt belongs to the third-party library of python and needs to be installed through pip

pip install xlwt

Write Excel data

1. First import the xlwt third-party library

2. Create a workbook module, which is equivalent to creating an xlwt file

3. Create a table through add_sheet

4. Use the write function to complete the write operation on the table

5. Import the written data into Excel

9349f1753f7cd9dbb0aece6c05ecf8a9.png

 openpyxl

OpenPyXl is a Python module that can be used to process excel tables

Install:

xlrd is a third-party library of python, which needs to be installed through pip

pip install openpyxl

When using from openpyxl import Workbook or from openpyxl import load_workbook in the code


The difference is that the former does not need to have an excel file, while the latter needs to pass in an excel file


The former can generate one out of thin air, the latter cannot.


Write Excel data using openpyxl

1. Get workbook
2. Get the worksheet
3. Then get the cell to operate
4. Save the file

415d318f911a10652380fd59bf4084f1.png

 pandas

Write data in Excel except xlwt and openpyxl. Pandas can also achieve this function.

It incorporates a large number of libraries and some standard data models, provides the tools needed to efficiently operate large data sets, and enables us to process data quickly and easily. Next, let's take a look at how to read and write excel with pandas.

1. Read excel

Reading excel is mainly implemented through the read_excel function. In addition to pandas, a third-party library xlrd needs to be installed.

2. Write to excel

Writing to excel is mainly achieved by constructing a DataFrame through pandas and calling the to_excel method.

The data we are going to read today is some data from the Guazi second-hand car website crawled before. Some of the data are shown as follows:

c830f40a6b3b4152722228e3d6f79f1f.png

What we are going to show today is to use the three methods introduced above to write the data of the txt file into excel.

# 标题列表
columns = []
# 数据列表
datas = []

with open('二手车.txt', encoding='utf-8') as fin:
    # 首行判断
    is_first_line = True
    for line in fin:
        line = line[:-1]
        if is_first_line:
            is_first_line = False
            columns = line.split('\t')
            continue
        datas.append(line.split('\t'))

ic(columns)
ic(datas)

The read line list and data list data are displayed as follows:

35108d606323d76211a7aac65d94f154.png

The data is successfully read, and then we use three methods to write it into excel

Use xlwt to generate an excel file of xls

# 使用xlwt生成xls的excel文件
import xlwt

workbook = xlwt.Workbook(encoding='utf-8')
sheet = workbook.add_sheet('瓜子二手车')

for col, column in enumerate(columns):
    sheet.write(0, col, column)

for row, data in enumerate(datas):
    for col, column_data in enumerate(data):
        sheet.write(row+1, col, column_data)

workbook.save('瓜子二手车1.xls')

ef1e15a89d736365a2dfab46d9f17f9e.png

Use openpyxl to generate an excel file of xlsx

# 使用openpyxl生成xlsx的excel文件
from openpyxl import Workbook
workbook = Workbook()

sheet = workbook.active
sheet.title = '默认title'
sheet.append(columns)
for data in datas:
    sheet.append(data)
workbook.save('瓜子二手车2.xlsx')

05fdf332fe192d3b853e00158f067c9b.png

Use pandas to generate excel files of xlsx

# 使用pandas生成xlsx的excel文件
import pandas as pd
rcv_data = pd.read_csv('二手车.txt', sep='\t')
rcv_data.head()
ic(rcv_data)
rcv_data.to_excel('瓜子二手车3.xlsx', index = False)

d4c17aed8f25da726a156247892cfba0.png

The above are the three methods of writing data into excel that I will introduce to you today. This writing method is still in high demand in actual work, and interested friends can operate it.


Finally, I would like to recommend our member group, currently there are venture capital angel investors, headhunters HR, Douyin big V, emotional bloggers, lawyers, psychological counselors, medical sales, real estate, insurance, piano teachers, operators, business consulting, Students from cross-border e-commerce, construction, data analysts in the Internet industry, back-end development, python testing and other industries will join.

Great value for money planet

At present, there are 420+ people on the planet, and 41 cheats have been updated in the content of the column. Every day, planets publish their own experiences. You can learn for only one dollar:

Python: 44 lessons of python introductory course + 9 lessons of Django column + interesting practical cases

chatgpt: entry, advanced, fun office, advanced courses

AI painting: Mj's basics, entry, advanced, Xiaohongshu gameplay

If you want to learn Python, ChatGPT, and AI painting, and you just want to spend a little money, welcome to join our planet member group, and you can meet a lot of great people!

Join to send ChatGPT independent account

94ca01c8651f9fb9e13f6e1838fbb351.jpeg

Also send ChatGPT advanced video courses

The original price is 99, and now it is free to send planet members

3a5c2e75117cc666eccd9382a873f1dd.jpeg

WeChat long press to try the content

If you are not satisfied within three days, you can directly refund! ! !

0fd7a20bd15b4082f327c4763f44ea5c.png

推荐阅读:
入门: 最全的零基础学Python的问题  | 零基础学了8个月的Python  | 实战项目 |学Python就是这条捷径
干货:爬取豆瓣短评,电影《后来的我们》 | 38年NBA最佳球员分析 |   从万众期待到口碑扑街!唐探3令人失望  | 笑看新倚天屠龙记 | 灯谜答题王 |用Python做个海量小姐姐素描图 |碟中谍这么火,我用机器学习做个迷你推荐系统电影
趣味:弹球游戏  | 九宫格  | 漂亮的花 | 两百行Python《天天酷跑》游戏!
AI: 会做诗的机器人 | 给图片上色 | 预测收入 | 碟中谍这么火,我用机器学习做个迷你推荐系统电影
小工具: Pdf转Word,轻松搞定表格和水印! | 一键把html网页保存为pdf!|  再见PDF提取收费! | 用90行代码打造最强PDF转换器,word、PPT、excel、markdown、html一键转换 | 制作一款钉钉低价机票提示器! |60行代码做了一个语音壁纸切换器天天看小姐姐!|

Guess you like

Origin blog.csdn.net/cainiao_python/article/details/131179392