利用Python開發(fā)Markdown表格結構轉換為Excel工具
在數(shù)據(jù)管理和文檔編寫過程中,我們經常使用 Markdown 來記錄表格數(shù)據(jù)。然而,Markdown 格式的表格在實際應用中不如 Excel 方便,特別是需要進一步處理數(shù)據(jù)時。因此,我們開發(fā)了一個使用 wxPython 的 GUI 工具,將 Markdown 表格結構轉換為 Excel 文件。

1.完整代碼
import wx
import re
import openpyxl
import logging
class MarkdownToExcelApp(wx.Frame):
def __init__(self):
super().__init__(parent=None, title='Markdown 轉 Excel', size=(800, 600))
# 配置日志
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
filename='markdown_to_excel_debug.log',
filemode='w')
# 創(chuàng)建面板
panel = wx.Panel(self)
# 創(chuàng)建垂直布局
main_sizer = wx.BoxSizer(wx.VERTICAL)
# 輸入標簽
input_label = wx.StaticText(panel, label='請輸入Markdown表格結構:')
main_sizer.Add(input_label, 0, wx.ALL | wx.EXPAND, 10)
# 輸入文本框
self.input_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
main_sizer.Add(self.input_text, 1, wx.ALL | wx.EXPAND, 10)
# 轉換按鈕
convert_btn = wx.Button(panel, label='轉換為Excel')
convert_btn.Bind(wx.EVT_BUTTON, self.on_convert)
main_sizer.Add(convert_btn, 0, wx.ALL | wx.CENTER, 10)
# 日志文本框
self.log_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE | wx.TE_READONLY)
main_sizer.Add(self.log_text, 1, wx.ALL | wx.EXPAND, 10)
# 設置面板的布局
panel.SetSizer(main_sizer)
# 創(chuàng)建菜單欄
menubar = wx.MenuBar()
file_menu = wx.Menu()
exit_item = file_menu.Append(wx.ID_EXIT, '退出', '退出應用程序')
menubar.Append(file_menu, '文件')
self.SetMenuBar(menubar)
# 綁定菜單事件
self.Bind(wx.EVT_MENU, self.on_exit, exit_item)
# 居中顯示
self.Centre()
def log_and_display(self, message):
"""記錄日志并在界面顯示"""
logging.debug(message)
self.log_text.AppendText(message + '\n')
def parse_markdown_structure(self, markdown_text):
"""解析Markdown表格結構"""
self.log_and_display("開始解析Markdown表格結構")
# 存儲表格信息的字典
table_structure = {}
# 按表格分割
table_blocks = markdown_text.split('* **')
for block in table_blocks[1:]: # 跳過第一個空元素
# 分割表格名稱和字段
lines = block.split('\n')
table_name = lines[0].strip()
# 提取字段
fields = []
for line in lines[1:]:
line = line.strip()
if line.startswith('* '):
# 移除 '* ' 前綴
fields.append(line[2:].strip())
self.log_and_display(f"表格: {table_name}")
self.log_and_display(f"字段: {fields}")
# 存儲表格結構
table_structure[table_name] = fields
self.log_and_display(f"解析完成,總表格數(shù): {len(table_structure)}")
return table_structure
def on_convert(self, event):
"""轉換Markdown結構到Excel"""
# 清空之前的日志
self.log_text.Clear()
markdown_text = self.input_text.GetValue()
if not markdown_text.strip():
wx.MessageBox('請輸入Markdown表格結構', '錯誤', wx.OK | wx.ICON_ERROR)
return
try:
# 解析Markdown結構
table_structure = self.parse_markdown_structure(markdown_text)
# 創(chuàng)建工作簿
wb = openpyxl.Workbook()
# 為每個表格創(chuàng)建sheet
first_sheet = True
for table_name, fields in table_structure.items():
self.log_and_display(f"創(chuàng)建sheet: {table_name}")
if first_sheet:
# 重命名第一個sheet
ws = wb.active
ws.title = table_name.split(' ')[0][:31] # Excel sheet名稱長度限制
first_sheet = False
else:
ws = wb.create_sheet(title=table_name.split(' ')[0][:31])
# 寫入表頭
for col, field in enumerate(fields, start=1):
ws.cell(row=1, column=col, value=field)
# 添加一個示例行(可選)
for col, field in enumerate(fields, start=1):
ws.cell(row=2, column=col, value=f"示例{field}")
# 保存文件
save_dialog = wx.FileDialog(
self,
"保存Excel文件",
wildcard="Excel文件 (*.xlsx)|*.xlsx",
style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT
)
if save_dialog.ShowModal() == wx.ID_OK:
filename = save_dialog.GetPath()
wb.save(filename)
self.log_and_display(f'Excel文件已保存:{filename}')
wx.MessageBox(f'Excel文件已保存:{filename}', '成功', wx.OK | wx.ICON_INFORMATION)
save_dialog.Destroy()
except Exception as e:
error_msg = f'轉換出錯:{str(e)}'
self.log_and_display(error_msg)
wx.MessageBox(error_msg, '錯誤', wx.OK | wx.ICON_ERROR)
def on_exit(self, event):
"""退出應用程序"""
self.Close(True)
def main():
app = wx.App()
frame = MarkdownToExcelApp()
frame.Show()
app.MainLoop()
if __name__ == '__main__':
main()
2. 項目概述
本項目提供一個圖形界面,用戶可以輸入 Markdown 格式的表格結構,程序解析后生成 Excel 文件。該應用具備以下功能:
- 支持 Markdown 格式的表格結構解析。
- 生成 Excel 文件,每個表格對應一個工作表。
- 記錄日志,方便調試。
- 提供 GUI 界面,用戶體驗友好。
3. 代碼解析
3.1 依賴庫
import wx import re import openpyxl import logging
wx 用于創(chuàng)建 GUI 界面。
re 用于正則表達式解析 Markdown 表格。
openpyxl 用于創(chuàng)建 Excel 文件。
logging 記錄調試信息。
3.2 GUI 設計
class MarkdownToExcelApp(wx.Frame):
def __init__(self):
super().__init__(parent=None, title='Markdown 轉 Excel', size=(800, 600))
wx.Frame 創(chuàng)建主窗口,標題為“Markdown 轉 Excel”。
設置窗口大小為 800x600。
# 配置日志
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
filename='markdown_to_excel_debug.log',
filemode='w')
記錄日志到 markdown_to_excel_debug.log,用于調試。
# 創(chuàng)建面板 panel = wx.Panel(self) # 創(chuàng)建垂直布局 main_sizer = wx.BoxSizer(wx.VERTICAL)
wx.Panel 是 GUI 的容器。
wx.BoxSizer(wx.VERTICAL) 采用垂直布局管理組件。
3.3 解析 Markdown 結構
def parse_markdown_structure(self, markdown_text):
self.log_and_display("開始解析Markdown表格結構")
table_structure = {}
table_blocks = markdown_text.split('* **')
for block in table_blocks[1:]:
lines = block.split('\n')
table_name = lines[0].strip()
fields = [line[2:].strip() for line in lines[1:] if line.startswith('* ')]
self.log_and_display(f"表格: {table_name}")
self.log_and_display(f"字段: {fields}")
table_structure[table_name] = fields
self.log_and_display(f"解析完成,總表格數(shù): {len(table_structure)}")
return table_structure
split('* **') 將 Markdown 文本按表格名稱分割。
逐行解析字段。
記錄日志信息。
3.4 生成 Excel
def on_convert(self, event):
markdown_text = self.input_text.GetValue()
if not markdown_text.strip():
wx.MessageBox('請輸入Markdown表格結構', '錯誤', wx.OK | wx.ICON_ERROR)
return
try:
table_structure = self.parse_markdown_structure(markdown_text)
wb = openpyxl.Workbook()
first_sheet = True
for table_name, fields in table_structure.items():
ws = wb.active if first_sheet else wb.create_sheet(title=table_name.split(' ')[0][:31])
first_sheet = False
for col, field in enumerate(fields, start=1):
ws.cell(row=1, column=col, value=field)
ws.cell(row=2, column=col, value=f"示例{field}")
save_dialog = wx.FileDialog(self, "保存Excel文件", wildcard="Excel文件 (*.xlsx)|*.xlsx", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if save_dialog.ShowModal() == wx.ID_OK:
filename = save_dialog.GetPath()
wb.save(filename)
self.log_and_display(f'Excel文件已保存:{filename}')
wx.MessageBox(f'Excel文件已保存:{filename}', '成功', wx.OK | wx.ICON_INFORMATION)
except Exception as e:
self.log_and_display(f'轉換出錯:{str(e)}')
wx.MessageBox(f'轉換出錯:{str(e)}', '錯誤', wx.OK | wx.ICON_ERROR)openpyxl.Workbook() 創(chuàng)建 Excel 文件。
create_sheet() 創(chuàng)建多個表格,每個表格對應一個工作表。
wx.FileDialog 讓用戶選擇文件保存路徑。
logging 記錄轉換過程。
3.5 退出應用
def on_exit(self, event):
self.Close(True)
關閉應用。
4. 運行程序
def main():
app = wx.App()
frame = MarkdownToExcelApp()
frame.Show()
app.MainLoop()
if __name__ == '__main__':
main()
啟動 wxPython GUI。
5. 總結
本項目通過 wxPython 構建用戶界面,并結合 openpyxl 解析 Markdown 表格并生成 Excel 文件。它適用于希望從 Markdown 結構化數(shù)據(jù)導出 Excel 的用戶,簡化了手動整理表格的過程。
你可以進一步優(yōu)化該項目,如:
增加 Markdown 語法校驗。
允許用戶調整 Excel 文件格式。
增加數(shù)據(jù)預覽功能。
6.運行結果


以上就是利用Python開發(fā)Markdown表格結構轉換為Excel工具的詳細內容,更多關于Python Markdown轉Excel的資料請關注腳本之家其它相關文章!
相關文章
python安裝win32com.client的實現(xiàn)示例
win32com.client是Python操作Windows COM對象的模塊,用于與Office交互,本文主要介紹了python安裝win32com.client的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下2025-06-06
jupyter notebook tensorflow打印device信息實例
這篇文章主要介紹了jupyter notebook tensorflow打印device信息實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
使用Pytorch Geometric進行鏈接預測的實現(xiàn)代碼
PyTorch Geometric (PyG)是構建圖神經網絡模型和實驗各種圖卷積的主要工具,在本文中我們將通過鏈接預測來對其進行介紹,文中有詳細的代碼示例供大家參考,需要的朋友可以參考下2023-10-10

