專業(yè)微信網(wǎng)站建設(shè)公司首選公司全網(wǎng)營銷推廣方案外包
文章目錄
- 安裝模塊
- 讀取Excel
- 數(shù)據(jù)庫取數(shù)
- 匹配數(shù)據(jù)和更新Excel數(shù)據(jù)
在Ubuntu系統(tǒng)的環(huán)境下基本職能借助Python的openpyxl模塊實現(xiàn)對Excel數(shù)據(jù)的操作。
安裝模塊
本次需要用到的模塊需要提前安裝(如果沒有的話)
pip3 install openpyxl
pip3 install pymysql
在操作前,需要準(zhǔn)備好用于操作的Excel文件,假設(shè)其文件名為 example.xlsx
。
此外,還需準(zhǔn)備好相應(yīng)的數(shù)據(jù)庫,本文以MySQL 5.7數(shù)據(jù)庫為例,確保數(shù)據(jù)庫中包含相應(yīng)的數(shù)據(jù)表及數(shù)據(jù)。
讀取Excel
使用openpyxl模塊讀取Excel文件中的數(shù)據(jù),可參考以下代碼示例:
from openpyxl import load_workbook# 加載Excel文件
workbook = load_workbook('example.xlsx')# 選擇活動工作表
sheet = workbook.active# 讀取數(shù)據(jù)并存儲
rows = sheet.max_row
cols = sheet.max_column
data_list = []
for row in range(1, rows + 1):row_data = []for col in range(1, cols + 1):cell_value = sheet.cell(row=row, column=col).valuerow_data.append(cell_value)data_list.append(row_data)# 顯示讀取的數(shù)據(jù)
for row in data_list:print(row)
上述代碼將Excel文件中的數(shù)據(jù)讀取并存儲到 data_list
列表中,以便后續(xù)與數(shù)據(jù)庫數(shù)據(jù)進(jìn)行匹配。
數(shù)據(jù)庫取數(shù)
以下是連接數(shù)據(jù)庫并進(jìn)行簡單查詢的代碼示例:
import pymysql# 連接數(shù)據(jù)庫
connection = pymysql.connect(host='localhost',user='root',password='your_password',database='your_database',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor
)try:with connection.cursor() as cursor:# 查詢數(shù)據(jù)search_value = data_list[0][0] # 以data_list第一個元素的第一列的值作為搜索條件sql = "SELECT * FROM your_table WHERE some_column = %s"cursor.execute(sql, (search_value,))result = cursor.fetchall()# 顯示匹配結(jié)果for row in result:print(row)
finally:connection.close()
在使用過程中,需要根據(jù)實際情況修改連接參數(shù)及查詢語句中的相關(guān)字段。
匹配數(shù)據(jù)和更新Excel數(shù)據(jù)
假設(shè)匹配到的數(shù)據(jù)存儲在 result
列表中,現(xiàn)在需要將匹配結(jié)果更新回Excel數(shù)據(jù)中,具體操作如下:
from openpyxl import Workbook# 創(chuàng)建新的工作簿
workbook = load_workbook('example.xlsx')
sheet = workbook.active# 寫入表頭信息
sheet['A'] = '原數(shù)據(jù)'
sheet['B'] = '匹配結(jié)果'# 將原數(shù)據(jù)和新列寫入Excel
for i, row in enumerate(data_list, start=1):sheet.cell(row=i, column=1).value = rowmatched = Falsefor res in result:if row[0] == res['col']: # 假設(shè)匹配字段在第一列且數(shù)據(jù)庫查詢結(jié)果字段名為'col'sheet.cell(row=i, column=2).value = '匹配成功'matched = Truebreakif not matched:sheet.cell(row=i, column=2).value = '無匹配數(shù)據(jù)'# 保存更新后的新工作簿
workbook.save('matched_data.xlsx')