python openpyxl 讀寫excel

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)  # 新建工作表

# 行列都是從1開始,cell就是一個單元格,給定單元格行列和寫入值就可以
# 寫入表頭
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
# 讀取txt,遍歷圖片,計算圖片長寬和RGB並存入excel
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

# 保存到.xlsx文件中
file.save('hw_rgb.xlsx')

4. 讀取

  • 寫入第一步,讀取表格
  • 第二步,獲取工作表sheet
  • 第三步,給定行列號獲取cell的value值
import openpyxl
import numpy as np

file = 'hw_rgb.xlsx'

# 讀取表格
wb = openpyxl.load_workbook(file)
# 獲取工作表sheet
active_sheet = wb['Sheet1']

# 獲取表格最大行列數
row = active_sheet.max_row
col = active_sheet.max_column


hw = []
rgb = []

# 循環讀取sheet數據,並存入列表
# 注意:比如最大行得到20,但是實際上只有19行,最後一行是空的,所以下main是row-1
for r in range(row-1):
    r = r + 2  # +2是因爲for循環從0開始,因此加1,去除表頭,再次加1
	
	# 指定行列號,獲取該cell的value
    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)])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章