如何使用 Python 將 Excel 文件導入資料庫表
在今天這個資料驅動的世界中,高效處理和處理資料是任何組織或個人必須的任務。 Python,其豐富的程式庫生態系統,提供強大工具進行資料操控和管理,如pandas程式庫。 一個常見的情境是需要從Excel電子表格中提取或導入資料,並將資料儲存或插入到資料庫中,以進行進一步的分析或與其他系統的整合。 在本教程中,我們將探索如何建立一個Python腳本來自動化此過程,讓您無縫地從Excel表文件中讀取資料並將其插入到資料庫中。 完成本教程後,您將能夠有效地處理資料遷移任務。 讓我們開始吧!
如何使用Python將Excel文件導入到資料庫表中
- 首先安裝IronXL程式庫。
- 使用IronXL將您的Excel文件載入記憶中。
- 載入您希望使用的特定電子表格。
- 選擇您打算匯入的精確資料範圍。
- 使用Python與任何資料庫建立連接,如SQLite或MySQL連接資料庫。
- 在您的SQLite資料庫中建立一個新表以容納導入的資料。
- 將選中的Excel文件中的行插入到新建立的SQLite表中。
- 從建立的SQLite資料庫表中檢索並選擇資料以進一步分析或處理。
在本教程中,我們將使用IronXL,這是一個以高效處理Excel文件而聞名的Python程式庫。 通過將IronXL整合到我們的腳本中,我們確保Excel表中的資料無縫提取,並能順利插入到資料庫中以便進一步分析和處理。
什麼是IronXL?
IronXL是由Iron Software開發的一個Python程式庫,提供強大的功能以在Python應用中直接閱讀、生成和編輯Excel文件。 特別是,IronXL因不依賴於Microsoft Excel安裝而脫穎而出,簡化了在不同環境中的部署。 使用IronXL,開發人員可以享受以下好處:
跨平台支援:在Windows、macOS、Linux、Docker、Azure和AWS平台上無縫運作,確保適應各種開發環境。
資料導入和導出:輕鬆處理來自XLS、XLSX、CSV和TSV文件的資料導入,並能夠將工作表輸出到這些格式,甚至到JSON,以提高互操作性。
加密功能:通過IronXL的加密功能確保資料安全,允許以密碼保護XLSX、XLSM和XLTX文件。
公式和重新計算:運用Excel公式不費力氣,並在每次編輯表時自動重新計算,確保資料操控的準確性和可靠性。
單元格樣式:通過調整字型樣式、大小、背景圖案、邊框和對齊方式來自訂單元格外觀,提升Excel文件的視覺呈現。
廣泛的文件格式支援:支援各種格式包括XLS、XLSX、XLST、XLSM、CSV、TSV,IronXL使開發者能夠輕鬆高效地處理多種情境中的資料。
現在,讓我們開始安裝IronXL。
步驟1:安裝IronXL程式庫
第一步是安裝IronXL程式庫。 在命令提示符中運行以下命令以安裝IronXL。
pip install IronXLpip install IronXL步驟2:載入Excel工作簿
下一步是載入Excel文件。我們將使用以下Excel文件進行本教程。

以下程式碼將現有Excel文件載入記憶中。
from ironxl import * # Supported for XLSX, XLS, XLSM, XLTX, CSV, and TSV
# Assign a license key (retrieved from IronXL website)
License.LicenseKey = "IRONSUITE.ABC.XYZ.COM.15796-DEPLOYMENT.TRIAL-5X63V4.TRIAL.EXPIRES.27.MAY.2024"
# Load the Excel workbook into memory
workbook = WorkBook.Load("sample_excel.xlsx")from ironxl import * # Supported for XLSX, XLS, XLSM, XLTX, CSV, and TSV
# Assign a license key (retrieved from IronXL website)
License.LicenseKey = "IRONSUITE.ABC.XYZ.COM.15796-DEPLOYMENT.TRIAL-5X63V4.TRIAL.EXPIRES.27.MAY.2024"
# Load the Excel workbook into memory
workbook = WorkBook.Load("sample_excel.xlsx")上述Python程式碼片段演示如何使用IronXL程式庫載入名為"sample_excel.xlsx"的Excel工作簿。 首先,從IronXL中導入必要的Python模組。 接著,分配授權金鑰以驗證程式庫的使用。 您可以從IronXL網站獲取您的免費授權金鑰。 最後,使用Load方法開啟並載入指定的Excel工作簿到記憶中。 這使得其內容的後續程式處理變得可能,例如讀取資料、修改單元格值或應用格式。
步驟3:選擇工作表
要使用IronXL選擇Excel工作簿中的工作表,您可以指定工作表的索引或名稱。
# Select the first worksheet in the loaded Excel workbook
worksheet = workbook.WorkSheets[0]# Select the first worksheet in the loaded Excel workbook
worksheet = workbook.WorkSheets[0]此行選擇載入的Excel工作簿中的第一個工作表,並將其分配給變數worksheet,以便對工作簿中的特定工作表執行後續操作。 這將把Excel表中的資料載入到工作表變數中。
步驟4:開啟資料庫連接
在本教程中,我們使用SQLite資料庫而不是MySQL資料庫伺服器。 為了開始資料庫操作,我們從建立資料庫連接開始。
import sqlite3
# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('data.db')import sqlite3
# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('data.db')上述行建立了名為'data.db'的SQLite資料庫連接。 如果指定的資料庫不存在,將自動建立。 這個連接使得後續與SQLite資料庫的互動成為可能,例如執行查詢和進行資料操控操作。
步驟5:建立表
下一步是建立資料庫中的資料表,我們將從Excel文件中匯入資料。要在SQLite資料庫中建立表,您可以使用連接物件執行SQL語句。
# Create a cursor object for database operations
cursor = conn.cursor()
# Define and execute SQL to create a table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS customer (
id INTEGER,
FirstName TEXT,
LastName TEXT,
Gender TEXT,
Country TEXT,
Age INTEGER
)
''')# Create a cursor object for database operations
cursor = conn.cursor()
# Define and execute SQL to create a table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS customer (
id INTEGER,
FirstName TEXT,
LastName TEXT,
Gender TEXT,
Country TEXT,
Age INTEGER
)
''')上述程式碼片段初始化一個cursor物件,以便在SQLite資料庫連接中執行SQL命令。 它建立了一個名為'customer'的表,其中包含'id'、'FirstName'、'LastName'、'Gender'、'Country'和'Age'列。 如果表不存在,則根據指定的列資料型別建立該表。
步驟6:使用Python將資料導入資料庫
現在,我們將資料插入到我們新建立的表中。 我們將匯入一個Excel文件,並將其資料插入到SQLite資料庫中。
# Iteratively insert data from Excel worksheet into SQLite database
for i in range(2, 11):
# Extracting values from columns A to F in Excel worksheet
values_tuple = (
worksheet[f"A{i}"].StringValue,
worksheet[f"B{i}"].StringValue,
worksheet[f"C{i}"].StringValue,
worksheet[f"D{i}"].StringValue,
worksheet[f"E{i}"].StringValue,
worksheet[f"F{i}"].StringValue
)
# Executing SQL INSERT command
cursor.execute("INSERT INTO customer VALUES (?, ?, ?, ?, ?, ?)", values_tuple)
# Commit data insertion to the database
conn.commit()# Iteratively insert data from Excel worksheet into SQLite database
for i in range(2, 11):
# Extracting values from columns A to F in Excel worksheet
values_tuple = (
worksheet[f"A{i}"].StringValue,
worksheet[f"B{i}"].StringValue,
worksheet[f"C{i}"].StringValue,
worksheet[f"D{i}"].StringValue,
worksheet[f"E{i}"].StringValue,
worksheet[f"F{i}"].StringValue
)
# Executing SQL INSERT command
cursor.execute("INSERT INTO customer VALUES (?, ?, ?, ?, ?, ?)", values_tuple)
# Commit data insertion to the database
conn.commit()上述程式碼迭代Excel工作表中的第2到10行,提取每行A到F列的值。 這些值儲存在一個元組中,代表要插入到'customer'表中的資料。 cursor然後執行一個SQL INSERT命令,將值元組插入表中。 這個過程對每一行重複執行,有效地將Excel文件中的資料匯入到SQLite資料庫中。 最後,conn.commit()提交交易,確保更改被儲存並持久化到資料庫中。
步驟7:從資料庫讀取資料
要確認資料是否正確插入,您可以使用SELECT查詢從SQLite資料庫中的'customer'表讀取資料。 例如:
# Execute a SELECT query to retrieve all data from the 'customer' table
cursor.execute("SELECT * FROM customer")
# Fetch all rows from the result set
rows = cursor.fetchall()
# Print each row to verify inserted data
for row in rows:
print(row)
# Close the database connection to release resources
conn.close()# Execute a SELECT query to retrieve all data from the 'customer' table
cursor.execute("SELECT * FROM customer")
# Fetch all rows from the result set
rows = cursor.fetchall()
# Print each row to verify inserted data
for row in rows:
print(row)
# Close the database connection to release resources
conn.close()上述程式碼執行一個'SELECT'查詢在SQLite資料庫的'customer'表上,檢索所有行。 獲取的行使用fetchall()方法儲存在'rows'變數中。 然後,逐行列印顯示插入到'customer'表中的資料。 最後,使用close()方法關閉資料庫連接以釋放資源。

完整的程式碼如下:
import sqlite3
from ironxl import * # Supported for XLSX, XLS, XLSM, XLTX, CSV, and TSV
# Assign a license key (retrieved from IronXL website)
License.LicenseKey = "IRONSUITE.ABC.XYZ.COM.15796-DEPLOYMENT.TRIAL-5X63V4.TRIAL.EXPIRES.27.MAY.2024"
# Load the Excel workbook into memory
workbook = WorkBook.Load("sample_excel.xlsx")
# Select worksheet at index 0
worksheet = workbook.WorkSheets[0]
# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('data.db')
# Create a cursor object for database operations
cursor = conn.cursor()
# Define and execute SQL to create a table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS customer (
id INTEGER,
FirstName TEXT,
LastName TEXT,
Gender TEXT,
Country TEXT,
Age INTEGER
)
''')
# Clear any existing data from the table
cursor.execute("DELETE FROM customer")
# Iteratively insert data from Excel worksheet into SQLite database
for i in range(2, 11):
# Extracting values from columns A to F in Excel worksheet
values_tuple = (
worksheet[f"A{i}"].StringValue,
worksheet[f"B{i}"].StringValue,
worksheet[f"C{i}"].StringValue,
worksheet[f"D{i}"].StringValue,
worksheet[f"E{i}"].StringValue,
worksheet[f"F{i}"].StringValue
)
# Executing SQL INSERT command
cursor.execute("INSERT INTO customer VALUES (?, ?, ?, ?, ?, ?)", values_tuple)
# Commit data insertion to the database
conn.commit()
# Execute a SELECT query to retrieve all data from the 'customer' table
cursor.execute("SELECT * FROM customer")
# Fetch all rows from the result set
rows = cursor.fetchall()
# Print each row to verify inserted data
for row in rows:
print(row)
# Close the database connection to release resources
conn.close()import sqlite3
from ironxl import * # Supported for XLSX, XLS, XLSM, XLTX, CSV, and TSV
# Assign a license key (retrieved from IronXL website)
License.LicenseKey = "IRONSUITE.ABC.XYZ.COM.15796-DEPLOYMENT.TRIAL-5X63V4.TRIAL.EXPIRES.27.MAY.2024"
# Load the Excel workbook into memory
workbook = WorkBook.Load("sample_excel.xlsx")
# Select worksheet at index 0
worksheet = workbook.WorkSheets[0]
# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('data.db')
# Create a cursor object for database operations
cursor = conn.cursor()
# Define and execute SQL to create a table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS customer (
id INTEGER,
FirstName TEXT,
LastName TEXT,
Gender TEXT,
Country TEXT,
Age INTEGER
)
''')
# Clear any existing data from the table
cursor.execute("DELETE FROM customer")
# Iteratively insert data from Excel worksheet into SQLite database
for i in range(2, 11):
# Extracting values from columns A to F in Excel worksheet
values_tuple = (
worksheet[f"A{i}"].StringValue,
worksheet[f"B{i}"].StringValue,
worksheet[f"C{i}"].StringValue,
worksheet[f"D{i}"].StringValue,
worksheet[f"E{i}"].StringValue,
worksheet[f"F{i}"].StringValue
)
# Executing SQL INSERT command
cursor.execute("INSERT INTO customer VALUES (?, ?, ?, ?, ?, ?)", values_tuple)
# Commit data insertion to the database
conn.commit()
# Execute a SELECT query to retrieve all data from the 'customer' table
cursor.execute("SELECT * FROM customer")
# Fetch all rows from the result set
rows = cursor.fetchall()
# Print each row to verify inserted data
for row in rows:
print(row)
# Close the database connection to release resources
conn.close()結論
總之,這個教程演示了資料操作的自動化方法,尤其是提取和插入Excel資料到資料庫。 這個過程不僅提高了資料管理的效率,也充分發掘了資料處理工作的潛能。 運用Python和IronXL的強大,優化您的資料工作流程,並自信地推進您的項目發展。
常見問題
如何使用Python將Excel文件中的資料匯入資料庫?
您可以使用IronXL程式庫將Excel文件中的資料匯入資料庫,首先通過`WorkBook.Load()`載入Excel文件,然後選擇工作表並建立與SQLite的資料庫連接以插入資料。
在Python中使用IronXL處理Excel文件的好處是什麼?
IronXL允許您在不需要安裝Microsoft Excel的情況下處理Excel文件,支持跨平臺操作,提供加密和公式重算等強大功能,並高效管理資料提取和插入過程。
如何為Python專案安裝IronXL?
要為Python專案安裝IronXL,您可以使用命令:`pip install IronXL`。這將把IronXL新增到您的Python環境中,讓您能夠高效地處理Excel文件。
是否可以在無Microsoft Excel安裝的情況下處理Python中的Excel文件?
是的,使用IronXL,您可以在無需安裝Microsoft Excel的情況下處理Excel文件。IronXL提供了讀取、編輯和寫入Excel文件所需的所有功能。
在Python中建立資料庫表以儲存Excel資料的過程是什麼?
要在Python中建立資料庫表,您可以使用SQLite的`sqlite3`模組。在使用`connect()`建立連接後,透過游標物件執行SQL的`CREATE TABLE`語句。
如何驗證Excel資料是否已成功插入SQLite資料庫?
您可以透過在表上執行`SELECT`查詢並使用`fetchall()`方法檢索和列印結果集中的所有行來驗證插入。
使用Python進行資料從Excel到資料庫的遷移應遵循什麼步驟?
步驟包括安裝IronXL、載入Excel文件、選擇工作表、連接資料庫、建立表格,並迭代Excel的行以使用SQL的`INSERT`命令插入資料。
IronXL能否處理Excel公式並在Python中重算它們?
是的,IronXL支持Excel公式並能重算它們,提供了一個綜合的解決方案來在Python應用中操作Excel文件。
在處理Excel文件時,IronXL是否支持跨平臺操作?
是的,IronXL支持跨平臺操作,包括Windows、macOS、Linux、Docker、Azure和AWS等環境,使其成為各種開發設置下的多功能選擇。
IronXL如何在Python應用程式中增強資料工作流程?
IronXL通過提供高效的資料提取、操作和插入能力來增強資料工作流程,優化資料管理流程,並改善資料驅動應用程式的性能。









