一、讀取Excel文件
Excel文件一般使用第三方庫xlrd進行讀取。參數包括文件路徑、指定工作表等。
import xlrd
def read_excel(file_path, sheet_name):
# 打開文件
workbook = xlrd.open_workbook(file_path)
# 獲取指定工作表
sheet = workbook.sheet_by_name(sheet_name)
# 獲取行數和列數
nrows = sheet.nrows
ncols = sheet.ncols
# 讀取數據
data = []
for i in range(nrows):
row_data = []
for j in range(ncols):
row_data.append(sheet.cell_value(i,j))
data.append(row_data)
return data
使用示例:
file_path = "/path/to/file.xlsx"
sheet_name = "Sheet1"
data = read_excel(file_path, sheet_name)
print(data)
二、將Excel數據轉換為XML格式
將Excel數據轉換為XML格式,需要按照XML的格式要求進行構造,在Python中可以通過minidom庫實現。
from xml.dom import minidom
def create_xml(data):
# 創建XML文檔對象
doc = minidom.Document()
# 創建根元素
root = doc.createElement("root")
doc.appendChild(root)
# 創建數據元素
for row_data in data:
row = doc.createElement("row")
root.appendChild(row)
for j in range(len(row_data)):
cell = doc.createElement("cell%s" % j)
cell_text = doc.createTextNode(str(row_data[j]))
cell.appendChild(cell_text)
row.appendChild(cell)
# 返回XML字元串
return doc.toprettyxml(indent=" ")
使用示例:
data = [['A1', 'B1', 'C1'], ['A2', 'B2', 'C2'], ['A3', 'B3', 'C3']]
xml_str = create_xml(data)
print(xml_str)
三、將XML字元串寫入文件
將XML字元串寫入文件,需要使用Python內置的open()函數進行文件操作。
def write_xml(xml_str, file_path):
with open(file_path, "w") as f:
f.write(xml_str)
使用示例:
xml_str = create_xml(data)
file_path = "/path/to/file.xml"
write_xml(xml_str, file_path)
四、完整示例
將上述代碼整合,形成Excel轉XML的完整示例。
import xlrd
from xml.dom import minidom
def read_excel(file_path, sheet_name):
# 打開文件
workbook = xlrd.open_workbook(file_path)
# 獲取指定工作表
sheet = workbook.sheet_by_name(sheet_name)
# 獲取行數和列數
nrows = sheet.nrows
ncols = sheet.ncols
# 讀取數據
data = []
for i in range(nrows):
row_data = []
for j in range(ncols):
row_data.append(sheet.cell_value(i,j))
data.append(row_data)
return data
def create_xml(data):
# 創建XML文檔對象
doc = minidom.Document()
# 創建根元素
root = doc.createElement("root")
doc.appendChild(root)
# 創建數據元素
for row_data in data:
row = doc.createElement("row")
root.appendChild(row)
for j in range(len(row_data)):
cell = doc.createElement("cell%s" % j)
cell_text = doc.createTextNode(str(row_data[j]))
cell.appendChild(cell_text)
row.appendChild(cell)
# 返回XML字元串
return doc.toprettyxml(indent=" ")
def write_xml(xml_str, file_path):
with open(file_path, "w") as f:
f.write(xml_str)
if __name__ == "__main__":
file_path = "/path/to/file.xlsx"
sheet_name = "Sheet1"
xml_file_path = "/path/to/file.xml"
data = read_excel(file_path, sheet_name)
xml_str = create_xml(data)
write_xml(xml_str, xml_file_path)
五、總結
通過闡述Excel轉XML的過程,我們詳細講解了如何使用Python中的第三方庫xlrd實現對Excel文件的讀取,以及如何使用minidom庫進行XML格式的構造,最後將XML字元串寫入文件。這些知識點可以幫助開發者在實際項目中快速處理Excel數據。
原創文章,作者:SCRKB,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/331736.html