python操作excel并封装成exe文件_十一、使用QTableWidget,openpyxl处理excel,并打包为exe...
目錄
一、背景介紹
二、代碼及成果
三、代碼分析
四、打包為exe
本實(shí)例主要使用了QTableWidget,openpyxl,利用openpyxl實(shí)現(xiàn)對(duì)excel文件的讀取,QTableWidget實(shí)現(xiàn)對(duì)excel文件內(nèi)容讀取后,擇需要信息在窗體上顯示。之所以寫該代碼,是因?yàn)樵谕豁?xiàng)目的設(shè)計(jì)過程中(本人的工作是水工設(shè)計(jì)),常使用緯地軟件設(shè)計(jì)多段道路,每段道路的數(shù)模都會(huì)生成土方計(jì)算表,軟件的默認(rèn)命名難以區(qū)分樁號(hào),且挖填方量需要依次點(diǎn)開各個(gè)excel文件查看,不太方便。該段代碼專門處理緯地軟件生成的土方計(jì)算表,功能有
自動(dòng)獲取樁號(hào),并批量將文件以起止樁號(hào)重命名
自動(dòng)批量計(jì)算總挖填方,并將各段路的方量顯示在QTableWidget中。
一、背景介紹
緯地軟件生成的土方計(jì)算表通常會(huì)給定默認(rèn)命名(如下圖),我懶得一個(gè)個(gè)去改,但是僅根據(jù)默認(rèn)據(jù)文件名難以確定是那段樁號(hào)的文件。如果改成以樁號(hào)來命名,方便最后統(tǒng)計(jì)工程量
緯地生成的土方計(jì)算表,同一個(gè)工作簿內(nèi)通常有多個(gè)工作表,但最后一個(gè)是沒有用的。需要從每個(gè)工作表的A列提取樁號(hào),然后再倒數(shù)第二個(gè)工作表內(nèi)提取累計(jì)的挖方量和填方量。
二、代碼及成果
主要代碼及操作界面如下
from PyQt5.QtWidgets importQWidget, QApplication, QFileDialog, QPushButton, QLineEdit, QHBoxLayout, \
QVBoxLayout, QLabel, QTableWidget, QHeaderView, QTableWidgetItemfrom PyQt5.QtGui importQIconimportsys, os, openpyxl
path= os.path.dirname(os.path.dirname(__file__))classMyWin(QWidget):def __init__(self):
super(MyWin, self).__init__()
self.initui()definitui(self):
self.setWindowTitle('土方計(jì)算表計(jì)算')
self.setWindowIcon(QIcon(r'%s\4.mypython\chuan.ico' %path))
self.resize(600, 500)
btn_open= QPushButton('打開文件')
btn_rename= QPushButton('重命名')
lbl_excavation= QLabel('總挖方量', self)
lineedit_excavation=QLineEdit()
lbl_fill= QLabel('總填方量', self)
lineedit_fill=QLineEdit()
tableWidget=QTableWidget()#=======布局======
hbx1 =QHBoxLayout()
hbx1.addWidget(lbl_excavation)
hbx1.addWidget(lineedit_excavation)
hbx1.addWidget(lbl_fill)
hbx1.addWidget(lineedit_fill)
hbx1.addWidget(btn_open)
hbx1.addWidget(btn_rename)
vbx=QVBoxLayout()
vbx.addWidget(tableWidget)
vbx.addLayout(hbx1)
self.setLayout(vbx)
btn_rename.clicked.connect(self.rename_files)
btn_open.clicked.connect(lambda: self.open_files(lineedit_excavation, lineedit_fill, tableWidget)) #調(diào)用函數(shù)
#btn_open.clicked.connect(lambda: self.table_init(tableWidget))
defrename_files(self):
f_names, _= QFileDialog.getOpenFileNames(self, '打開文件', 'D:\\', 'XLSX Files(*.xlsx)')if f_names: #f_names返回值為列表,元素為文件地址
for f_name inf_names:
wb= openpyxl.load_workbook(f_name) #打開工作簿
stake_numbers =[]for sheetname in wb.sheetnames[:-1]: #依次獲取工作表,提取起止樁號(hào)。最后一個(gè)工作表無內(nèi)容,因此舍去
ws =wb[sheetname]
stake_numbers+= [i.value for i in ws['A'] if i.value != None][4:-2] #獲取樁號(hào)列表
start_station, end_station = stake_numbers[0], stake_numbers[-1] #賦值起點(diǎn)樁號(hào)和終點(diǎn)樁號(hào)
os.rename(f_name.split('/')[-1], '%s~%s.xlsx' % (start_station, end_station)) #os.rename(舊名字,新名字)
defopen_files(self, lineedit_excavation, lineedit_fill, table):
f_names, _= QFileDialog.getOpenFileNames(self, '打開文件', 'D:\\', 'XLSX Files(*.xlsx)')iff_names:
total_excavation, total_fill=0, 0
self.quantity_all= [] #起止樁號(hào)和挖填方
for f_name inf_names:
wb= openpyxl.load_workbook(f_name, data_only=True) #只返回?cái)?shù)值,不返回公式
#cell_range = ws['A1':'C2'] #通過切片訪問多個(gè)單元格
ws = wb[wb.sheetnames[-2]]
quantity_fill, quantity_excavation= ws['R37'].value, ws['E37'].value
total_excavation+=quantity_excavation
total_fill+=quantity_fill
stake_numbers=[]for sheetname in wb.sheetnames[:-1]: #依次獲取工作表,提取起止樁號(hào)。最后一個(gè)工作表無內(nèi)容,因此舍去
ws =wb[sheetname]
stake_numbers+= [i.value for i in ws['A'] if i.value != None][4:-2] #獲取樁號(hào)列表
start_station, end_station = stake_numbers[0], stake_numbers[-1] #賦值起點(diǎn)樁號(hào)和終點(diǎn)樁號(hào)
self.quantity_all.append(
[start_station, end_station, round(quantity_excavation,2), round(quantity_fill, 2)])
lineedit_excavation.setText(str(round(total_excavation,2))) #必須轉(zhuǎn)換為字符串才能賦值
lineedit_fill.setText(str(round(total_fill, 2))) #必須轉(zhuǎn)換為字符串才能賦值
self.table_init(table)deftable_init(self, table):
table.setColumnCount(4)
table.setRowCount(len(self.quantity_all))
table.setHorizontalHeaderLabels(['起點(diǎn)樁號(hào)', '終點(diǎn)樁號(hào)', '挖方量', '填方量'])
table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)#print(self.quantity_all)
for i inrange(len(self.quantity_all)):for j in range(4):
newitem= QTableWidgetItem(str(self.quantity_all[i][j])) #必須轉(zhuǎn)成字符串,否則不報(bào)錯(cuò),也不顯示
table.setItem(i, j, newitem)if __name__ == '__main__':
app=QApplication(sys.argv)
win=MyWin()
win.show()
sys.exit(app.exec_())
批量處理土方計(jì)算表
處理后的文件:
三、代碼分析
f_names, _ = QFileDialog.getOpenFileNames(self, '打開文件', 'D:\\', 'XLSX Files(*.xlsx)')
這里_為占位符,f_names范圍的是元組,元素為各個(gè)文件的絕對(duì)路徑。如果使用getOpenFileName就只能打開單個(gè)文件,getOpenFileNames可以打開多個(gè)文件,實(shí)現(xiàn)批量處理。
stake_numbers += [i.value for i in ws['A'] if i.value != None][4:-2]
這里使用了列表生成器,if i.value != None可以將空白單元格排除掉
wb = openpyxl.load_workbook(f_name, data_only=True)
這里必須加data_only=True,因?yàn)閑xcel里有些單元格是有公式的,不加這個(gè)返回的就是單元格的公式而不是單元格的值。
table.setRowCount(len(self.quantity_all)) #行數(shù)隨文件自動(dòng)變化
table.setHorizontalHeaderLabels(['起點(diǎn)樁號(hào)', '終點(diǎn)樁號(hào)', '挖方量', '填方量'])
table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) #列寬自動(dòng)拉伸
四、打包為exe
可以使用pyinstaller將代碼打包為exe。windows平臺(tái)打包后,想要運(yùn)行時(shí)不彈出cmd窗口,步驟如下,
1.將文件名改為pyw后綴,例如“表格.py”改為“表格.pyw”
2.啟動(dòng)cmd,切換到py文件所在目錄
3. 輸入pyinstaller -F 表格.pyw --noconsole 這里的“表格.pyw”是要打包的py文件名,“--noconsole”必須要加上,這樣程序運(yùn)行時(shí)不會(huì)彈出cmd窗口
總結(jié)
以上是生活随笔為你收集整理的python操作excel并封装成exe文件_十一、使用QTableWidget,openpyxl处理excel,并打包为exe...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Elasticsearch 7.7.0
- 下一篇: python高级--数据分析(Panda