[Python] Write data to excel file

Purpose:

Python implements writing data into excel files.

step:

1. Import the dependent package xlwt
Note: The xlwt here is a third-party module of python, which needs to be downloaded and installed before it can be used (if it is not installed, you can directly enter pip install xlwt in the terminal to install it).
2. Create an excel form file
3. Create a sheet form in the excel form type file
4. Write the specified value into the sheet
5. Save the excel

Example:

import numpy as np
import xlwt
# 随机生成一个3×4的数组(值不超过10)
data = np.random.randint(10, size=(3, 4))
# 创建excel表格类型文件
book = xlwt.Workbook(encoding='utf-8', style_compression=0)
# 在excel表格类型文件中建立一张sheet表单
sheet = book.add_sheet('sheet1', cell_overwrite_ok=True)

for i in range(data.shape[0]): #逐行
    for j in range(data.shape[1]): #逐列
        sheet.write(i, j, data[i][j]) #将指定值写入第i行第j列

save_path = './data.xls'
book.save(save_path)

Among them, view data:

print(data)

[[2 1 9 3]
[7 6 7 3]
[9 4 8 4]]
View the saved excel file:
insert image description here
You can add custom column names (row headers, column headers, etc.) as needed.

# 添加自定义列名
col = ['编号', '数值1', '数值2', '数值3', '数值4']
for c in range(len(col)):
    sheet.write(0, c, col[c]) #在第0行写入列名
for i in range(data.shape[0]): #逐行
    sheet.write(i + 1, 0, i + 1) #在第0列写入编号
    for j in range(data.shape[1]): #逐列
        sheet.write(i + 1, j + 1, str(data[i][j])) #将指定值写入第i+1行第j+1列
save_path = './data.xls'
book.save(save_path)

View the saved excel file:
insert image description here
OK~

Guess you like

Origin blog.csdn.net/qq_40445009/article/details/130396876