python_Excel_xlwt
xlwt
创建excel,向excel写入数据,并保存数据
安装
推荐方法:
通过pip 安装,方便简洁,如下图所示:
导入
import xlrd
创建workbook(即excel)
book = Workbook(encoding='utf-8')#create a workbook
创建sheet
sheet = book.add_sheet('Sheet1')#create a sheet
设置样式
#set style
font = xlwt.Font() # 字体
font.name = 'Times New Roman'
font.bold = True
font.underline = False
font.italic = False
style = xlwt.XFStyle() # 创建一个格式
style.font = font # 设置格式字体
往单元格写入
sheet.write(0, 0, "no",style)#第1行,第1列
sheet.write(0, 1, "file_name",style)#第1行,第2列
sheet.write(0, 2, "file_version",style)#第1行,第3列
保存
book.save(save_path)
- #coding=utf-8
- '''
- Created on 2018年11月12日
- @author: yanerfree
- get the version number of the file (.dll/.exe) in bulk
- 批量获取文件版本号,适合量少的,因为是单线程
- '''
- import os
- import sys
- import win32api
- import xlwt
- from xlwt import *
- import time
- from PyQt5.QtGui import *
- from PyQt5.QtWidgets import *
- from PyQt5.QtCore import *
- #测试调试输出开关,正式发布需调整为False
- mytest = True
- mytest = False
- class GetFileVersionNo(QWidget):
- def __init__(self):
- super().__init__()
- self.setupUi()
- self.myList = []#save result
- self.status = 0#记录目前是否在获取版本状态下
- def setupUi(self):
- glayout = QGridLayout()
- glayout.setSpacing(10)
- self.button1 = QPushButton("需要获取版本号的文件路径")
- self.button1.clicked.connect(self.open_dir)
- self.button2 = QPushButton("选择文件保存位置")
- self.button2.clicked.connect(self.save_file_dialog)
- self.lineEdit1 = QLineEdit()
- self.lineEdit2 = QLineEdit()
- self.button3 = QPushButton("获取版本号")
- #self.button3.setCheckable(True)
- self.button3.clicked.connect(self.getVer)
- self.textEdit1 = QTextEdit()
- self.label1 = QLabel(" 选择文件类型:")
- self.combobox1 = QComboBox()
- self.combobox1.addItem("exe")
- self.combobox1.addItem("dll")
- self.combobox1.currentTextChanged.connect(self.textEdit1.clear)
- glayout.addWidget(self.button1,1,1)
- glayout.addWidget(self.button2,2,1)
- glayout.addWidget(self.label1,3,1)
- glayout.addWidget(self.combobox1,3,2)
- glayout.addWidget(self.button3,4,1)
- glayout.addWidget(self.lineEdit1,1,2,1,2)
- glayout.addWidget(self.lineEdit2,2,2,1,2)
- glayout.addWidget(self.textEdit1,4,2,10,2)
- self.setGeometry(20,50,500,450)
- self.setWindowTitle("GetFileVersionNo")#设置窗体标题
- self.setLayout(glayout)
- def getVer(self):
- if self.status == 0:
- self.textEdit1.clear()
- self.status = 1#状态设置为1,获取版本中
- self.changestatus()
- file_path = self.lineEdit1.text()
- if not os.path.exists(file_path):
- self.showMsg("warning","请选择正确的路径")
- return
- save_path = self.lineEdit2.text()
- if save_path == "":
- self.showMsg("warning","请选择结果保存路径")
- return
- tmp1 = str(save_path).split("/")[-1]
- #print("tmp:",tmp1)
- tmp2 = str(save_path).split(tmp1)[0]
- #print("tmp:",tmp2)
- if not os.path.exists(tmp2):
- self.showMsg("warning","请选择正确的保存路径")
- return
- self.writeToExcel(file_path,save_path)
- self.status = 0
- self.changestatus()
- else:
- self.showMsg("warning", "正在获取版本号,请等待...")
- def changestatus(self):
- if self.status == 0:
- self.myList=[]
- self.button1.setEnabled(True)
- self.button2.setEnabled(True)
- self.button3.setEnabled(True)
- else:
- self.button1.setEnabled(False)
- self.button2.setEnabled(False)
- self.button3.setEnabled(False)
- def open_dir(self):
- dir_path=QFileDialog.getExistingDirectory(self,"choose directory",r"C:\\")
- if not os.path.exists(dir_path):
- return -1
- #dir_path = self.dir_path.replace('/','\\')#windows下需要进行文件分隔符转换
- #将获取的路径写入lineedit中
- self.lineEdit1.setText(dir_path)
- return (dir_path)
- def save_file_dialog(self):
- save_fileName, ok2 = QFileDialog.getSaveFileName(self,
- "文件保存",
- r"C:\\",
- "Text Files (*.xls);;All Files (*)")
- #print("save_fileName,ok2:",save_fileName,ok2)
- #将获取的路径写入lineedit中
- self.lineEdit2.setText(save_fileName)
- return(save_fileName)
- def showMsg(self,t,msg):
- if(t=="warning"):
- QMessageBox.information(self,"warning",msg,QMessageBox.Yes,QMessageBox.Yes)
- self.status = 0#状态设置为1,获取版本中
- self.changestatus()
- def traverse_dir(self,file_path):
- #traverse the directory of file_path(the file are .dll)
- #myList=[]#save result,如果该函数递归调用,则不能在此处保存结果,
- #否则每次递归都会清楚之前保存的数据
- try:
- filelist = os.listdir(file_path)
- for i in range(0,len(filelist)):
- print(i,filelist[i])
- tmp_path = os.path.join(file_path,filelist[i])
- tmp_path = tmp_path.replace('/','\\')#windows下需要进行文件分隔符转换
- print("tmp_path:",tmp_path)
- if os.path.isfile(tmp_path):
- #if str(list[i]).split(".")[1] =="dll":
- #if str(filelist[i])[-3:] == "exe":
- print("self.combobox1.currentText():",self.combobox1.currentText())
- #print("str(filelist[i])[-3:]:",str(filelist[i])[-3:])
- if str(filelist[i])[-3:] == self.combobox1.currentText():
- #judge if the filename ended with ".dll"
- #print tmp_path,getFileVersion(tmp_path)
- print ("add to mylis",(filelist[i],self.getFileVersion(tmp_path)))
- self.myList.append((filelist[i],self.getFileVersion(tmp_path)))
- #将内容更新到textedit中去
- content = ""
- for item in self.myList:
- content = content + "%s %s\r\n"%(item[0],item[1])
- self.textEdit1.setText(content)
- else:
- self.traverse_dir(tmp_path)
- except:
- self.showMsg("warning","未知错误")
- self.myList = []
- return self.myList
- def getFileVersion(self,file_name):
- #get the version of file
- try:
- info = win32api.GetFileVersionInfo(file_name, os.sep)
- ms = info['FileVersionMS']
- ls = info['FileVersionLS']
- version = '%d.%d.%d.%04d' % (win32api.HIWORD(ms), win32api.LOWORD(ms), win32api.HIWORD(ls), win32api.LOWORD(ls))
- print("version:",version)
- except:
- version = " "
- return version
- def writeToExcel(self,file_path,save_path):
- #file_path = self.file_path
- #save_path = self.save_path
- #write to excel
- print("create a workbook")
- book = Workbook(encoding='utf-8')#create a workbook
- sheet = book.add_sheet('Sheet1')#create a sheet
- #set style
- font = xlwt.Font() # 字体
- font.name = 'Times New Roman'
- font.bold = True
- font.underline = False
- font.italic = False
- style = xlwt.XFStyle() # 创建一个格式
- style.font = font # 设置格式字体
- #sheet.write(0, 0, label = 'Formatted value', style) # Apply the Style to the Cell
- sheet.write(0, 0, "no",style)
- sheet.write(0, 1, "file_name",style)
- sheet.write(0, 2, "file_version",style)
- list = self.traverse_dir(file_path)
- row=0
- num=0
- for item in list:
- row += 1
- num += 1
- print(item[0] ,item[1])
- sheet.write(row, 0, num, style)
- sheet.write(row, 1,item[0] , style)
- sheet.write(row, 2,item[1] , style)
- book.save(save_path)
- if __name__ == '__main__':
- app = QApplication(sys.argv)
- demo = GetFileVersionNo()
- demo.show()
- sys.exit(app.exec_())
python_Excel_xlwt的更多相关文章
随机推荐
- 解决Vue-cli3.0下scss文件编译过慢、卡顿问题
在使用Vue-cli 3.0构建的项目中,可能存在项目编译过慢的问题,具体表现在编译时会在某一进度比如40%时停顿,等好一会儿才能够编译完成.这使得浏览器中的实时预览也会卡顿,不利于我们快速查看效果, ...
- 洛谷P3018 [USACO11MAR]树装饰Tree Decoration
洛谷P3018 [USACO11MAR]树装饰Tree Decoration树形DP 因为要求最小,我们就贪心地用每个子树中的最小cost来支付就行了 #include <bits/stdc++ ...
- 解决vue渲染时闪烁{{}}的问题
原文转自: 点我 Vue页面加载时v-show设置的隐藏元素出现导致页面闪烁问题在写APP社区页面的时候在一些地方用了v-show,在刷新页面的时候就发现即便在逻辑判断为false某些元素不该显示时也 ...
- 刷短视频看新闻看小说也能赚钱的几款APP
一.抖音极速版 发啦! 刷短视频也能赚钱 第1步:下载[抖音极速版] 第2步:填我邀请码[831008243] 第3步:立刻提现最高[38元]红包 二.今日头条极速版 1元现金速撸 下载[今日头条极速 ...
- docker部署gitlab
Docker部署gitlab 一.前提条件 (1) 存在docker (2) 服务器可以联网(外网) (3) 服务器内存至少4G(内存不够会出现502错误) 内存不足502错误 ...
- 深度学习环境搭建:window10+CUDA10.0+CUDNN+pytorch1.2.0
去年底入手一台联想Y7000P,配置了Nvidia GeForce GTX 1660 Ti GPU,GPU内存6G,但是因为有GPU服务器,所以一直没有在这台笔记本上跑过模型,如今经过一番折腾,终于在 ...
- 【SpringBoot 基础系列】实现一个自定义配置加载器(应用篇)
[SpringBoot 基础系列]实现一个自定义配置加载器(应用篇) Spring 中提供了@Value注解,用来绑定配置,可以实现从配置文件中,读取对应的配置并赋值给成员变量:某些时候,我们的配置可 ...
- 多重背包转化成完全背包 E - Charlie's Change
http://poj.org/problem?id=1787 这个题目我一看就觉得是一个多重背包,但是呢,我不知道怎么输出路径,所以无可奈何,我就只能看一下题解了. 看了题解发现居然是把多重背包转化成 ...
- 模板引擎 Thymeleaf 动态渲染 HTML
1.添加依赖 <!-- Thymeleaf 模板引擎 --> <dependency> <groupId>org.thymeleaf</groupId> ...
- 生产者消费者问题中的同步机制JAVA设计和实现
目录 问题描述 问题分析 利用记录型信号量解决 运行环境 实现思路 代码实现 运行截图 过程中出现的问题和注意点 利用AND信号集解决 运行环境 实现思路 代码实现 运行截图 问题描述 若干进程通过有 ...