Python reads, writes, appends to Excel files and reads data through pandas to write pictures to Excel files

1. Read the Excel file pip install xlrd download command

import xlrd

# 打开文件
workbook = xlrd.open_workbook(r'D:\PycharmProjects\reptile\XLSX 工作表 .xlsx')
# 获取所有sheet
print(workbook.sheet_names())  # ['sheet1', 'sheet2']
# 根据sheet索引或者名称获取sheet内容
sheet1 = workbook.sheet_by_index(0)  # sheet索引从0开始
print('222', sheet1.name, sheet1.nrows, sheet1.ncols)  # sheet1的名称,行数,列数

order_oumber = sheet1.cell_value(2, 3)  # 第三行第四列

# 获取整行和整列的值(数组)
rows = sheet1.row_values(4)  # 获取第四行内容
cols = sheet1.col_values(3)  # 获取第三列内容
print('333', rows)
print('444', cols)

# 获取单元格内容,三种方法
print(sheet1.cell(1, 3).value.encode('utf-8'))
print(sheet1.cell_value(1, 3))
print(sheet1.row(1)[3])

2. Write the Excel file pip install xlwt download command

import xlwt

"""这种方法会清空文件原有的内容"""
workbook = xlwt.Workbook(encoding='utf-8')
booksheet = workbook.add_sheet('Sheet 1', cell_overwrite_ok=True)
# 存第一行cell(1,1)和cell(1,2)
booksheet.write(0, 0, 34)  # 第一行第一列
booksheet.write(0, 2, 55)  # 第一行第三列
booksheet.write(2, 2, 555)  # 第三行第三列
rowdata = [12, 13, 14]
for i in range(len(rowdata)):
    booksheet.write(8, i, rowdata[i])  # 第9行1,2,3列存入12,13,14
workbook.save('XLSX 工作表111.xlsx')  # 保存文件名

3. Additional write to Excel file pip install xlutils download command & do not open the file when prompted to save the file, otherwise an error will be reported

from xlutils.copy import copy

"""这种是追加写入数据,不清空原有的数据"""
workbook1 = xlrd.open_workbook(r'D:\PycharmProjects\reptile\XLSX 工作表  - 副本.xlsx')  # 文件路径
xlsc = copy(workbook1)
shtc = xlsc.get_sheet(0)
# (行,列,要追加的值)
shtc.write(5, 1, "追加得数11")
shtc.write(5, 5, "追加得数22")
shtc.write(5, 9, "追加得数33")
shtc.write(5, 8, "追加得数44")
xlsc.save('XLSX 工作表  - 副本.xlsx')  # 保存文件名

4. Read data through pandas pip install pandas download command

import pandas as pd

"""存数据"""
csv_mat = pd.np.empty((0, 2), float)
csv_mat = pd.np.append(csv_mat, [[43, 55]], axis=0)
csv_mat = pd.np.append(csv_mat, [[65, 67]], axis=0)
csv_pd = pd.DataFrame(csv_mat)
csv_pd.to_csv("tests.csv", sep=',', header=False, index=False)

"""取数据"""
filename = r"D:\PycharmProjects\reptile\tests.csv"
csv_data = pd.read_csv(filename, header=None)
csv_data = pd.np.array(csv_data, dtype=float)

5. Write the picture into an Excel file

import xlsxwriter


for i in range(1, 21):
    book = xlsxwriter.Workbook("000 .xls")		# 保存的文件名
    sheet = book.add_worksheet('demo')			
    print(i)
    sheet.insert_image('B' + str(i), r"D:\PycharmProjects\reptile\图片\\" + str(i) + '.jpg')	# 存入表格的位置和图片的路径
    book.close()

This method does not add to write pictures, save the pictures will clear other content, additional methods to be studied next update

Copy and paste the above code can be used

Guess you like

Origin blog.csdn.net/weixin_43407092/article/details/90315606