1. 爲什麼要用openpyxl
- 之前寫入ecxel一直習慣使用
xlwt
,最近寫入行數達到60萬行,而xlwt
僅支持寫入65535行,其保存格式是xls
。
- 因此,有必要找一個支持更大寫入量的python excel讀寫庫,就選擇了這個
openpyxl
,其寫入格式是xlsx
。
2. 安裝
pip install openpyxl
3. 寫入
- 寫入第一步,新建表格
- 第二步,新建工作表sheet
- 第三步,寫入數據,給定行列號和value值
- 第四步,保存表格
import cv2
import numpy as np
import openpyxl
txtpath= r'b1_train_cls.txt'
file = openpyxl.Workbook()
table = file.create_sheet(index=0)
table.cell(row = 1, column = 1, value = 'height')
table.cell(row = 1, column = 2, value = 'width')
table.cell(row = 1, column = 3, value = 'channnel')
table.cell(row = 1, column = 4, value = 'red')
table.cell(row = 1, column = 5, value = 'green')
table.cell(row = 1, column = 6, value = 'blue')
num = 2
for line in open(txtpath):
line = line.strip()
line_split = line.split(' ')
image_path = line_split[0]
img = cv2.imread(image_path, cv2.COLOR_BGR2RGB)
height, width, channnel = img.shape[0], img.shape[1], img.shape[2]
img_mean = np.mean(img, axis=(0, 1))
table.cell(row = num, column = 1, value = height)
table.cell(row = num, column = 2, value = width)
table.cell(row = num, column = 3, value = channnel)
table.cell(row = num, column = 4, value = img_mean[0])
table.cell(row = num, column = 5, value = img_mean[1])
table.cell(row = num, column = 6, value = img_mean[2])
num += 1
file.save('hw_rgb.xlsx')
4. 讀取
- 寫入第一步,讀取表格
- 第二步,獲取工作表sheet
- 第三步,給定行列號獲取cell的value值
import openpyxl
import numpy as np
file = 'hw_rgb.xlsx'
wb = openpyxl.load_workbook(file)
active_sheet = wb['Sheet1']
row = active_sheet.max_row
col = active_sheet.max_column
hw = []
rgb = []
for r in range(row-1):
r = r + 2
height = active_sheet.cell(row=r, column=2).value
width = active_sheet.cell(row=r, column=3).value
channnel= active_sheet.cell(row=r, column=4).value
red = active_sheet.cell(row=r, column=5).value
green = active_sheet.cell(row=r, column=6).value
blue = active_sheet.cell(row=r, column=7).value
hw.append([int(height), int(width)])
rgb.append([float(red), float(green), float(blue)])