python:openpyxl 读取 Excel文件,显示在 wx.grid 表格中

news/2024/7/21 5:50:01 标签: python, excel, openpyxl, wx.grid

pip install openpyxl
openpyxl-3.1.2-py2.py3-none-any.whl (249 kB)
et_xmlfile-1.1.0-py3-none-any.whl (4.7 kB)

摘要:A Python library to read/write Excel 2010 xlsx/xlsm files

pip install wxpython==4.2
wxPython-4.2.0-cp37-cp37m-win_amd64.whl (18.0 MB)
摘要: Cross platform GUI toolkit for Python, "Phoenix" version

编写 openpyxl_wx_grid.py 如下

python"># -*- coding: utf-8 -*-
""" openpyxl 读取.xlsx文件,显示在 wx.grid 表格中 """
import os
import sys
import datetime
import openpyxl
import wx
import wx.grid

class MyFrame(wx.Frame):

    def __init__(self):
        super().__init__(parent=None, title='openpyxl show on wx.grid', size=(1000,600))
        panel = wx.Panel(self)

        # 选择.xlsx文件名
        fileFilter = "Excel Files (*.xlsx)|*.xlsx"
        fileDialog = wx.FileDialog(self, message="选择xlsx文件", wildcard=fileFilter, style=wx.FD_OPEN)
        dialogResult = fileDialog.ShowModal()
        if dialogResult != wx.ID_OK:
            return
        filename = fileDialog.GetPath()
        if not os.path.exists(filename):
            print(f'Error: {filename} not found.')
            sys.exit(2)

        # Read Excel file
        book = openpyxl.load_workbook(filename, data_only=True)
        #sheet = book['Sheet1']
        sheet = book.active
        nrows = sheet.max_row    # 取最大行数
        if nrows > 10000:
            print(f" 行数: {nrows} > 10000 !")
            nrows = 10000
        ncols = sheet.max_column # 取最大列数
        if ncols > 26:
            print(f" columns: {ncols} > 26 !")
            ncols = 26

        # 创建一个表格
        self.grid = wx.grid.Grid(panel)
        self.grid.CreateGrid(nrows, ncols)  # 创建一个 nrows行 ncols列的表格

        # 设置表格的列标题
        cols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for j in range(0, ncols):
            self.grid.SetColLabelValue(j, cols[j])

        # 设置表格的行标题
        for i in range(0, nrows):
            self.grid.SetRowLabelValue(i, str(i+1))

        # 向表格中添加数据
        for i in range(0, nrows):
            for j in range(0, ncols):
                cell = sheet.cell(row=i+1,column=j+1)
                v = cell.value
                t = cell.data_type
                if v is None:
                    self.grid.SetCellValue(i,j, '')
                elif t in ('s','t'): # str, text
                    self.grid.SetCellValue(i,j, v)
                elif t =='n': # number
                    if v%1 ==0: # int
                        self.grid.SetCellValue(i,j, "%d" %v)
                    else: # float
                        self.grid.SetCellValue(i,j, "%.4f" %v)
                elif t =='d': # date
                    self.grid.SetCellValue(i,j, v.strftime('%Y-%m-%d'))
                else:
                    self.grid.SetCellValue(i,j, str(v))

        # 使用 sizer 来管理布局
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.grid, 1, wx.EXPAND | wx.ALL, 5)
        panel.SetSizer(sizer)


if __name__ == '__main__':
    app = wx.App()
    frame = MyFrame()
    frame.Show(True)
    app.MainLoop()

运行 python openpyxl_wx_grid.py

参考了百度:文心一言:openpyxl 示例 

一、load_workbook( ) 除了参数 filename 外为还有一些有用的参数:
load_workbook(filename, read_only=False, keep_vba=False, data_only=False, keep_links=True, rich_text=False)
read_only:是否为只读模式,对于超大型文件,要提升效率有帮助
keep_vba :是否保留 vba 代码,即打开 Excel 文件时,开启并保留宏
data_only:是否将公式转换为结果,即包含公式的单元格,是否显示最近的计算结果
keep_links:是否保留外部链接
rich_text: 是否保留富文本

二、读取公式:
如果使用 load_workbook() 方法在无参数的情况下打开一个Excel文件,并读取某单元格的值;
如果这个单元格本身的内容是公式,那么读取到的就是公式;如果这个单元格本身的内容是一个值,那么读取到的就是一个值。


三、读取公式计算后产生的数值
必须使用 load_workbook() 方法的 data_only=True 参数,例如:
work_book = openpyxl.load_workbook('test.xlsx', data_only=True)
这时,再去读取带公式的单元格,读取的 value 就是公式计算的结果了。


http://www.niftyadmin.cn/n/5068259.html

相关文章

Java方法案例

设计一个方法用于遍历数组,要求遍历的结果是在一行上的。例如:[11,22,33,44,55] public class index {public static void main(String[] args) {int[] arr {11,22,33,44,55};printArr(arr);}public static void printArr(int[] arr){System.out.print…

Net相关的各类开源项目

Net相关的各类开源项目 WPFHandyControlLive-ChartsWPFDeveloperswpf-uidesignStylet WebScheduleMasterYiShaAdminBlog.CoreNebula.AdminNewLife.CubeOpenAuth UnityuGUIUnityCsReferenceEpitomeMyUnityFrameWorkKSFrameworkTowerDefense-GameFramework-Demo 通用ClientServer…

国庆假期作业day2

作业&#xff1a;创建一个双向链表&#xff0c;将26个英文字母通过头插的方式插入到链表中&#xff0c;通过尾删的方式将数据读取出来并删除 #ifndef _TEXT_H #define _TEXT_H #include<myhead.h> typedef int datatype; typedef struct dblist {union {datatype data;/…

starrocks启动和停止和重启脚本

StarRocks启动和停止和重启脚本 编辑脚本&#xff1a;vim start_stop_starrocks.sh 备注:IP修改为自己的IP即可 #!/bin/bashcase $1 in "start"){for i in 12.3.7.147 12.3.7.148 12.3.7.149 12.3.7.150doecho " --------启动 $i be -------"ssh $i &qu…

101-视频与网络应用篇-教程内容

1.教程由来 笔者有一个正在读大学计算机应用专业的弟弟&#xff0c;之前在他大一&#xff0c;大二时反复提醒他&#xff0c;一定要学好专业知识&#xff0c;但是感觉没有任何效果&#xff0c;了解了一下学习情况&#xff0c;发现他的专业学习了解太差&#xff0c;眼看正读大三&…

指纹浏览器开发指南-EasyBR

想开发一款指纹浏览器&#xff0c;指纹浏览器名字叫做EasyBR&#xff0c;大致构思了下开发的步骤。 EasyBR指纹浏览器开发指南&#xff1a; 后台技术、前端技术和指纹修改 简介&#xff1a; EasyBR指纹浏览器是一款旨在提供个性化服务和广告定位的浏览器&#xff0c;通过收…

李沐深度学习记录3:11模型选择、欠拟合和过拟合

通过多项式拟合探索欠拟合与过拟合 import math import numpy as np import torch from torch import nn from d2l import torch as d2l#生成数据集 max_degree 20 # 多项式的最大阶数 n_train, n_test 100, 100 # 训练和测试数据集大小 true_w np.zeros(max_degree) # …

2020蜀山区,分数线230

Accepted P2635 平均年龄1263316 Accepted P2636 解密2093265 Accepted P2637 数字游戏&#xff08;number&#xff09;279195 Accepted P2638 寻宝1828265 平均年龄 1000ms 256MB 题目描述 新学期开学了&#xff0c;学校要统计各班同学的年龄&#xff0c;小莹莹…