鱼C论坛

 找回密码
 立即注册
查看: 2713|回复: 6

[已解决]求助Excel预览问题

[复制链接]
发表于 2023-5-22 21:50:34 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 hynet1024 于 2023-5-22 21:51 编辑

我想用Python做一个界面,通过资源管理器选择EXcel文件后,在指定的控件预览,请各路大神不吝赐教。

(图片只是设想的界面,不知道怎么写代码)
最佳答案
2023-5-22 22:31:07
hynet1024 发表于 2023-5-22 22:09
感谢大神赐教。有一个不甚完美的地方,就是预览的Excel文件格式不那么好看,能不能像原表格那样显示呢?

可以使用Pandas的`styling`功能,对表格进行美化,使其更接近原表格。具体实现方法如下:

1. 首先导入样式包:`from pandas.io.formats.style import Styler`
2. 在读取Excel数据后,创建一个Styler对象,并使用`.hide_index()`方法隐藏行索引
3. 调用`.set_table_styles()`方法设置表格样式,可以使用CSS样式或者dict格式来设置
4. 最后使用`.render()`方法将样式应用于表格并转化为HTML格式,再使用`.splitlines()`方法将HTML字符串分割为多行,并从第二行开始插入到Tkinter的Text组件中。

修改后的代码如下所示:



  1. import tkinter as tk
  2. from tkinter import filedialog
  3. import pandas as pd
  4. from pandas.io.formats.style import Styler

  5. class ExcelPreviewer:
  6.     def __init__(self, master):
  7.         self.master = master
  8.         master.title("Excel Previewer")
  9.         
  10.         # 创建文件选择器按钮
  11.         self.select_button = tk.Button(master, text="选择Excel文件", command=self.select_file)
  12.         self.select_button.pack(pady=10)
  13.         
  14.         # 创建文本框用于显示Excel数据
  15.         self.text = tk.Text(master, height=20, width=80)
  16.         self.text.pack()
  17.    
  18.     def select_file(self):
  19.         # 弹出文件选择器对话框
  20.         file_path = filedialog.askopenfilename(filetypes=[('Excel Files', '*.xlsx')])
  21.         if file_path:
  22.             # 使用Pandas读取Excel数据
  23.             df = pd.read_excel(file_path)
  24.             
  25.             # 使用Styler美化表格
  26.             styler = df.head(10).style.hide_index().set_table_styles([{
  27.                 'selector': 'th',
  28.                 'props': [
  29.                     ('border', '1px solid black'),
  30.                     ('background-color', 'lightgray'),
  31.                     ('color', 'black')
  32.                 ]
  33.             }, {
  34.                 'selector': 'td',
  35.                 'props': [
  36.                     ('border', '1px solid black'),
  37.                     ('padding', '5px')
  38.                 ]
  39.             }])
  40.             
  41.             # 在文本框中显示美化后的表格
  42.             self.text.delete(1.0, tk.END)
  43.             self.text.insert(tk.END, '\n'.join(styler.render().splitlines()[1:]))
  44.             

  45. root = tk.Tk()
  46. app = ExcelPreviewer(root)
  47. root.mainloop()
复制代码


这样就可以让预览的Excel文件格式更加美观,接近原表格。您可以根据需要进一步调整表格样式。
QQ图片20230522214954.png
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-5-22 21:55:46 | 显示全部楼层
您好!可以使用Python中的Tkinter模块来创建用户界面,使用Pandas来读取Excel文件。下面是一个简单的示例代码,它演示了如何选择Excel文件并在控件中预览数据:


  1. import tkinter as tk
  2. from tkinter import filedialog
  3. import pandas as pd

  4. class ExcelPreviewer:
  5.     def __init__(self, master):
  6.         self.master = master
  7.         master.title("Excel Previewer")
  8.         
  9.         # 创建文件选择器按钮
  10.         self.select_button = tk.Button(master, text="选择Excel文件", command=self.select_file)
  11.         self.select_button.pack(pady=10)
  12.         
  13.         # 创建文本框用于显示Excel数据
  14.         self.text = tk.Text(master, height=20, width=80)
  15.         self.text.pack()
  16.    
  17.     def select_file(self):
  18.         # 弹出文件选择器对话框
  19.         file_path = filedialog.askopenfilename(filetypes=[('Excel Files', '*.xlsx')])
  20.         if file_path:
  21.             # 使用Pandas读取Excel数据
  22.             df = pd.read_excel(file_path)
  23.             
  24.             # 在文本框中显示前10行数据
  25.             self.text.delete(1.0, tk.END)
  26.             self.text.insert(tk.END, df.head(10).to_string())
  27.             

  28. root = tk.Tk()
  29. app = ExcelPreviewer(root)
  30. root.mainloop()
复制代码

这个程序创建了一个名为“Excel Previewer”的窗口,在窗口中有一个“选择Excel文件”的按钮和一个文本框。点击按钮后会弹出文件选择器对话框,用户可以选择Excel文件。选择完成后程序会使用Pandas读取Excel文件的内容,并在文本框中显示前10行数据。您可以根据需要对代码进行修改,以适应您的具体需求。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-5-22 21:59:05 | 显示全部楼层
首先,为了预览Excel文件,你需要解析Excel文件。你可以使用开源库如 pandas 和 openpyxl 来读取和解析Excel文件。然后,你可以使用 Tkinter 或 PyQt 这样的图形用户界面(GUI)库来显示你解析的数据。

以下是一个基本的Tkinter和pandas结合的示例,你可以在这个基础上进行更多的定制和扩展:

  1. import tkinter as tk
  2. from tkinter import filedialog
  3. from pandas import read_excel
  4. import pandas as pd
  5. from pandastable import Table, TableModel

  6. def load_excel_data():
  7.     file_path = filedialog.askopenfilename(filetypes=(("Excel files", "*.xlsx"), ("All files", "*.*") ))
  8.     if file_path == '':
  9.         return
  10.     df = read_excel(file_path)
  11.     update_table(df)

  12. def update_table(df):
  13.     table.model.df = df
  14.     table.redraw()

  15. root = tk.Tk()
  16. main_frame = tk.Frame(root)
  17. main_frame.pack(fill='both', expand=True)

  18. table = Table(main_frame, dataframe=pd.DataFrame(), showtoolbar=True, showstatusbar=True)
  19. table.show()

  20. menu_bar = tk.Menu(root)
  21. file_menu = tk.Menu(menu_bar)
  22. menu_bar.add_cascade(label='File', menu=file_menu)
  23. file_menu.add_command(label='Open', command=load_excel_data)
  24. root.config(menu=menu_bar)

  25. root.mainloop()
复制代码


这段代码会创建一个窗口,窗口上方有一个菜单条,在菜单条中有一个“File”菜单。点击该菜单后会弹出一个文件对话框,让你选择一个Excel文件。选择文件后,会读取文件中的数据并在窗口中的表格中显示。

注意,这个例子使用了 pandastable 库来创建表格,这是一个可以在Tkinter界面中直接显示pandas数据框的库。

如果你的Python环境中没有 pandastable 库,你需要安装它。你可以在命令行中使用以下命令安装:

  1. pip install pandastable
复制代码


这个例子只是一个基本的起点,你可以根据你的需求对其进行扩展。例如,你可以添加更多的菜单项来执行其他操作,或者你可以添加更多的控件来显示其他信息。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-5-22 22:09:09 | 显示全部楼层
sfqxx 发表于 2023-5-22 21:55
您好!可以使用Python中的Tkinter模块来创建用户界面,使用Pandas来读取Excel文件。下面是一个简单的示例代 ...

感谢大神赐教。有一个不甚完美的地方,就是预览的Excel文件格式不那么好看,能不能像原表格那样显示呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-5-22 22:30:48 | 显示全部楼层
本帖最后由 isdkz 于 2023-5-22 22:34 编辑
hynet1024 发表于 2023-5-22 22:09
感谢大神赐教。有一个不甚完美的地方,就是预览的Excel文件格式不那么好看,能不能像原表格那样显示呢?


暂时只能这样了,没有研究出更好的方案

  1. import tkinter as tk
  2. from tkinter import filedialog
  3. from pandas import read_excel
  4. import pandas as pd
  5. from pandastable import Table, TableModel

  6. def browse_files():
  7.     file_path = filedialog.askopenfilename(filetypes=(("Excel files", "*.xlsx"), ("All files", "*.*") ))
  8.     if file_path == '':
  9.         return
  10.     file_path_entry.delete(0, tk.END)
  11.     file_path_entry.insert(0, file_path)

  12. def load_excel_data():
  13.     file_path = file_path_entry.get()
  14.     df = read_excel(file_path)
  15.     update_table(df)

  16. def update_table(df):
  17.     table.model.df = df
  18.     table.redraw()
  19.     table.setFontsize(10)
  20.     table.setFont('Calibri')
  21.     table.autoResizeColumns()
  22.     # Update table settings to make it look more like Excel
  23.     table.columncolors = 'white'
  24.     table.rowcolors = 'white'
  25.     table.grid_color = '#BFBFBF'
  26.     table.showGrid()

  27. root = tk.Tk()

  28. # create components
  29. browse_button = tk.Button(root, text="选择Excel文件", command=browse_files)
  30. file_path_entry = tk.Entry(root, width=50)
  31. confirm_button = tk.Button(root, text="确定", command=load_excel_data)

  32. # layout components
  33. browse_button.grid(row=0, column=0)
  34. file_path_entry.grid(row=0, column=1)
  35. confirm_button.grid(row=0, column=2)

  36. main_frame = tk.Frame(root)
  37. main_frame.grid(row=1, column=0, columnspan=3)

  38. table = Table(main_frame, dataframe=pd.DataFrame(), showtoolbar=True, showstatusbar=True)
  39. table.show()

  40. root.mainloop()

复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-5-22 22:31:07 | 显示全部楼层    本楼为最佳答案   
hynet1024 发表于 2023-5-22 22:09
感谢大神赐教。有一个不甚完美的地方,就是预览的Excel文件格式不那么好看,能不能像原表格那样显示呢?

可以使用Pandas的`styling`功能,对表格进行美化,使其更接近原表格。具体实现方法如下:

1. 首先导入样式包:`from pandas.io.formats.style import Styler`
2. 在读取Excel数据后,创建一个Styler对象,并使用`.hide_index()`方法隐藏行索引
3. 调用`.set_table_styles()`方法设置表格样式,可以使用CSS样式或者dict格式来设置
4. 最后使用`.render()`方法将样式应用于表格并转化为HTML格式,再使用`.splitlines()`方法将HTML字符串分割为多行,并从第二行开始插入到Tkinter的Text组件中。

修改后的代码如下所示:



  1. import tkinter as tk
  2. from tkinter import filedialog
  3. import pandas as pd
  4. from pandas.io.formats.style import Styler

  5. class ExcelPreviewer:
  6.     def __init__(self, master):
  7.         self.master = master
  8.         master.title("Excel Previewer")
  9.         
  10.         # 创建文件选择器按钮
  11.         self.select_button = tk.Button(master, text="选择Excel文件", command=self.select_file)
  12.         self.select_button.pack(pady=10)
  13.         
  14.         # 创建文本框用于显示Excel数据
  15.         self.text = tk.Text(master, height=20, width=80)
  16.         self.text.pack()
  17.    
  18.     def select_file(self):
  19.         # 弹出文件选择器对话框
  20.         file_path = filedialog.askopenfilename(filetypes=[('Excel Files', '*.xlsx')])
  21.         if file_path:
  22.             # 使用Pandas读取Excel数据
  23.             df = pd.read_excel(file_path)
  24.             
  25.             # 使用Styler美化表格
  26.             styler = df.head(10).style.hide_index().set_table_styles([{
  27.                 'selector': 'th',
  28.                 'props': [
  29.                     ('border', '1px solid black'),
  30.                     ('background-color', 'lightgray'),
  31.                     ('color', 'black')
  32.                 ]
  33.             }, {
  34.                 'selector': 'td',
  35.                 'props': [
  36.                     ('border', '1px solid black'),
  37.                     ('padding', '5px')
  38.                 ]
  39.             }])
  40.             
  41.             # 在文本框中显示美化后的表格
  42.             self.text.delete(1.0, tk.END)
  43.             self.text.insert(tk.END, '\n'.join(styler.render().splitlines()[1:]))
  44.             

  45. root = tk.Tk()
  46. app = ExcelPreviewer(root)
  47. root.mainloop()
复制代码


这样就可以让预览的Excel文件格式更加美观,接近原表格。您可以根据需要进一步调整表格样式。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-5-23 16:03:05 | 显示全部楼层
sfqxx 发表于 2023-5-22 22:31
可以使用Pandas的`styling`功能,对表格进行美化,使其更接近原表格。具体实现方法如下:

1. 首先导入 ...

感谢指点!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-24 00:00

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表