Python使用pandas讀取Excel并選取列轉(zhuǎn)json
1、背景介紹
大家都知道在利用Python對表格進行匹配的時候,我們進行會讀取一張Excel表格,然后選中其中的
某一列(或者多列)作為唯一項(key),
然后在選中
某一列(或者多列)作為值(value)
2、庫的安裝
| 庫 | 用途 | 安裝 |
|---|---|---|
| pandas | 讀取Excel文件 | pip install pandas -i https://pypi.tuna.tsinghua.edu.cn/simple/ |
| PyQt5 | 界面設(shè)計 | pip install PyQt5 -i https://pypi.tuna.tsinghua.edu.cn/simple/ |
| os | 獲取絕對路徑 | 內(nèi)置庫無需安裝 |
3、核心代碼
①:選擇 列
df = pd.read_excel(self.excel_file_path, dtype=str, keep_default_na=False)
headers = df.columns.tolist()
for i in reversed(range(self.key_checkboxes_layout.count())):
self.key_checkboxes_layout.itemAt(i).widget().setParent(None)
for i in reversed(range(self.value_checkboxes_layout.count())):
self.value_checkboxes_layout.itemAt(i).widget().setParent(None)
②:制作json
df['combined_key'] = df[key_cols].apply(lambda row: "=".join(row.values), axis=1)
df['combined_value'] = df[value_cols].apply(lambda row: "=".join(row.values), axis=1)
data = dict(zip(df['combined_key'], df['combined_value']))
with open(self.output_file_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
4、完整代碼
import os
import json
import pandas as pd
from PyQt5.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QLabel, QPushButton,
QFileDialog, QMessageBox, QCheckBox, QHBoxLayout
)
class ExcelToJsonApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("Excel 轉(zhuǎn) JSON 工具")
self.setGeometry(900, 500, 600, 500)
layout = QVBoxLayout()
self.folder_label = QLabel("選擇 Excel 文件:")
layout.addWidget(self.folder_label)
self.folder_button = QPushButton("選擇文件")
self.folder_button.clicked.connect(self.select_excel_file)
layout.addWidget(self.folder_button)
self.key_label = QLabel("請選擇鍵列(可多選):")
layout.addWidget(self.key_label)
self.key_checkboxes_layout = QVBoxLayout()
layout.addLayout(self.key_checkboxes_layout)
self.value_label = QLabel("請選擇值列(可多選):")
layout.addWidget(self.value_label)
self.value_checkboxes_layout = QVBoxLayout()
layout.addLayout(self.value_checkboxes_layout)
self.output_label = QLabel("選擇 JSON 輸出文件:")
layout.addWidget(self.output_label)
self.output_button = QPushButton("選擇文件")
self.output_button.clicked.connect(self.select_output_file)
layout.addWidget(self.output_button)
self.convert_button = QPushButton("轉(zhuǎn)換并保存")
self.convert_button.clicked.connect(self.convert_excel_to_json)
layout.addWidget(self.convert_button)
self.setLayout(layout)
def select_excel_file(self):
options = QFileDialog.Options()
file_path, _ = QFileDialog.getOpenFileName(self, "選擇 Excel 文件", "", "Excel 文件 (*.xls *.xlsx)",
options=options)
if file_path:
self.folder_label.setText(f"選中文件: {file_path}")
self.excel_file_path = file_path
self.load_excel_headers()
def load_excel_headers(self):
try:
df = pd.read_excel(self.excel_file_path, dtype=str, keep_default_na=False)
headers = df.columns.tolist()
for i in reversed(range(self.key_checkboxes_layout.count())):
self.key_checkboxes_layout.itemAt(i).widget().setParent(None)
for i in reversed(range(self.value_checkboxes_layout.count())):
self.value_checkboxes_layout.itemAt(i).widget().setParent(None)
self.key_checkboxes = []
self.value_checkboxes = []
for header in headers:
key_checkbox = QCheckBox(header)
self.key_checkboxes_layout.addWidget(key_checkbox)
self.key_checkboxes.append(key_checkbox)
value_checkbox = QCheckBox(header)
self.value_checkboxes_layout.addWidget(value_checkbox)
self.value_checkboxes.append(value_checkbox)
except Exception as e:
QMessageBox.warning(self, "錯誤", f"無法讀取 Excel 表頭: {e}")
def select_output_file(self):
options = QFileDialog.Options()
file_path, _ = QFileDialog.getSaveFileName(self, "保存 JSON 文件", "", "JSON 文件 (*.json)", options=options)
if file_path:
self.output_label.setText(f"輸出文件: {file_path}")
self.output_file_path = file_path
def convert_excel_to_json(self):
try:
key_cols = [cb.text() for cb in self.key_checkboxes if cb.isChecked()]
value_cols = [cb.text() for cb in self.value_checkboxes if cb.isChecked()]
if not hasattr(self, 'excel_file_path') or not hasattr(self, 'output_file_path'):
QMessageBox.warning(self, "錯誤", "請先選擇 Excel 文件和 JSON 輸出路徑!")
return
df = pd.read_excel(self.excel_file_path, dtype=str, keep_default_na=False)
for key_col in key_cols:
if key_col not in df.columns:
QMessageBox.warning(self, "錯誤", f"鍵列 {key_col} 不存在,請檢查!")
return
for value_col in value_cols:
if value_col not in df.columns:
QMessageBox.warning(self, "錯誤", f"值列 {value_col} 不存在,請檢查!")
return
df['combined_key'] = df[key_cols].apply(lambda row: "=".join(row.values), axis=1)
df['combined_value'] = df[value_cols].apply(lambda row: "=".join(row.values), axis=1)
data = dict(zip(df['combined_key'], df['combined_value']))
with open(self.output_file_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
QMessageBox.information(self, "成功", "轉(zhuǎn)換完成,JSON 已保存!")
except Exception as e:
QMessageBox.critical(self, "錯誤", f"處理文件時出錯: {e}")
if __name__ == "__main__":
app = QApplication([])
window = ExcelToJsonApp()
window.show()
app.exec_()
效果圖

以上就是Python使用pandas讀取Excel并選取列轉(zhuǎn)json的詳細內(nèi)容,更多關(guān)于Python Excel轉(zhuǎn)json的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
只用50行Python代碼爬取網(wǎng)絡(luò)美女高清圖片
第一次寫文章,技術(shù)不成熟之處望各位大神輕噴,今天教大家只用50行Python代碼爬取網(wǎng)絡(luò)美女圖片是怎么操作的,文中有非常詳細的代碼示例,對正在學(xué)習(xí)python的小伙伴們很有幫助哦,需要的朋友可以參考下2021-06-06
django之使用celery-把耗時程序放到celery里面執(zhí)行的方法
今天小編就為大家分享一篇django之使用celery-把耗時程序放到celery里面執(zhí)行的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
Python中str.format()和f-string的使用
本文主要介紹了Python中str.format()和f-string的使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
Python圖形化界面基礎(chǔ)篇之如何使用彈出窗口和對話框
對于Python程序員來說,處理彈出窗口似乎并不是一個常見的任務(wù),這篇文章主要給大家介紹了關(guān)于Python圖形化界面基礎(chǔ)篇之如何使用彈出窗口和對話框的相關(guān)資料,需要的朋友可以參考下2024-03-03

