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)

  1. #coding=utf-8
  2. '''
  3. Created on 2018年11月12日
  4.  
  5. @author: yanerfree
  6.  
  7. get the version number of the file (.dll/.exe) in bulk
  8. 批量获取文件版本号,适合量少的,因为是单线程
  9. '''
  10. import os
  11. import sys
  12. import win32api
  13. import xlwt
  14. from xlwt import *
  15. import time
  16. from PyQt5.QtGui import *
  17. from PyQt5.QtWidgets import *
  18. from PyQt5.QtCore import *
  19.  
  20. #测试调试输出开关,正式发布需调整为False
  21. mytest = True
  22. mytest = False
  23.  
  24. class GetFileVersionNo(QWidget):
  25. def __init__(self):
  26. super().__init__()
  27. self.setupUi()
  28. self.myList = []#save result
  29. self.status = 0#记录目前是否在获取版本状态下
  30.  
  31. def setupUi(self):
  32.  
  33. glayout = QGridLayout()
  34. glayout.setSpacing(10)
  35. self.button1 = QPushButton("需要获取版本号的文件路径")
  36. self.button1.clicked.connect(self.open_dir)
  37. self.button2 = QPushButton("选择文件保存位置")
  38. self.button2.clicked.connect(self.save_file_dialog)
  39. self.lineEdit1 = QLineEdit()
  40. self.lineEdit2 = QLineEdit()
  41. self.button3 = QPushButton("获取版本号")
  42. #self.button3.setCheckable(True)
  43. self.button3.clicked.connect(self.getVer)
  44. self.textEdit1 = QTextEdit()
  45.  
  46. self.label1 = QLabel(" 选择文件类型:")
  47. self.combobox1 = QComboBox()
  48. self.combobox1.addItem("exe")
  49. self.combobox1.addItem("dll")
  50. self.combobox1.currentTextChanged.connect(self.textEdit1.clear)
  51. glayout.addWidget(self.button1,1,1)
  52. glayout.addWidget(self.button2,2,1)
  53. glayout.addWidget(self.label1,3,1)
  54. glayout.addWidget(self.combobox1,3,2)
  55. glayout.addWidget(self.button3,4,1)
  56. glayout.addWidget(self.lineEdit1,1,2,1,2)
  57. glayout.addWidget(self.lineEdit2,2,2,1,2)
  58. glayout.addWidget(self.textEdit1,4,2,10,2)
  59.  
  60. self.setGeometry(20,50,500,450)
  61. self.setWindowTitle("GetFileVersionNo")#设置窗体标题
  62.  
  63. self.setLayout(glayout)
  64.  
  65. def getVer(self):
  66. if self.status == 0:
  67. self.textEdit1.clear()
  68. self.status = 1#状态设置为1,获取版本中
  69. self.changestatus()
  70. file_path = self.lineEdit1.text()
  71. if not os.path.exists(file_path):
  72. self.showMsg("warning","请选择正确的路径")
  73. return
  74.  
  75. save_path = self.lineEdit2.text()
  76. if save_path == "":
  77. self.showMsg("warning","请选择结果保存路径")
  78. return
  79. tmp1 = str(save_path).split("/")[-1]
  80. #print("tmp:",tmp1)
  81. tmp2 = str(save_path).split(tmp1)[0]
  82. #print("tmp:",tmp2)
  83. if not os.path.exists(tmp2):
  84. self.showMsg("warning","请选择正确的保存路径")
  85. return
  86.  
  87. self.writeToExcel(file_path,save_path)
  88. self.status = 0
  89. self.changestatus()
  90. else:
  91. self.showMsg("warning", "正在获取版本号,请等待...")
  92.  
  93. def changestatus(self):
  94. if self.status == 0:
  95. self.myList=[]
  96. self.button1.setEnabled(True)
  97. self.button2.setEnabled(True)
  98. self.button3.setEnabled(True)
  99.  
  100. else:
  101. self.button1.setEnabled(False)
  102. self.button2.setEnabled(False)
  103. self.button3.setEnabled(False)
  104.  
  105. def open_dir(self):
  106. dir_path=QFileDialog.getExistingDirectory(self,"choose directory",r"C:\\")
  107. if not os.path.exists(dir_path):
  108. return -1
  109. #dir_path = self.dir_path.replace('/','\\')#windows下需要进行文件分隔符转换
  110.  
  111. #将获取的路径写入lineedit中
  112. self.lineEdit1.setText(dir_path)
  113. return (dir_path)
  114.  
  115. def save_file_dialog(self):
  116. save_fileName, ok2 = QFileDialog.getSaveFileName(self,
  117. "文件保存",
  118. r"C:\\",
  119. "Text Files (*.xls);;All Files (*)")
  120. #print("save_fileName,ok2:",save_fileName,ok2)
  121. #将获取的路径写入lineedit中
  122. self.lineEdit2.setText(save_fileName)
  123.  
  124. return(save_fileName)
  125.  
  126. def showMsg(self,t,msg):
  127. if(t=="warning"):
  128. QMessageBox.information(self,"warning",msg,QMessageBox.Yes,QMessageBox.Yes)
  129. self.status = 0#状态设置为1,获取版本中
  130. self.changestatus()
  131.  
  132. def traverse_dir(self,file_path):
  133. #traverse the directory of file_path(the file are .dll)
  134. #myList=[]#save result,如果该函数递归调用,则不能在此处保存结果,
  135. #否则每次递归都会清楚之前保存的数据
  136. try:
  137. filelist = os.listdir(file_path)
  138. for i in range(0,len(filelist)):
  139. print(i,filelist[i])
  140. tmp_path = os.path.join(file_path,filelist[i])
  141. tmp_path = tmp_path.replace('/','\\')#windows下需要进行文件分隔符转换
  142. print("tmp_path:",tmp_path)
  143. if os.path.isfile(tmp_path):
  144. #if str(list[i]).split(".")[1] =="dll":
  145. #if str(filelist[i])[-3:] == "exe":
  146. print("self.combobox1.currentText():",self.combobox1.currentText())
  147. #print("str(filelist[i])[-3:]:",str(filelist[i])[-3:])
  148. if str(filelist[i])[-3:] == self.combobox1.currentText():
  149. #judge if the filename ended with ".dll"
  150. #print tmp_path,getFileVersion(tmp_path)
  151. print ("add to mylis",(filelist[i],self.getFileVersion(tmp_path)))
  152. self.myList.append((filelist[i],self.getFileVersion(tmp_path)))
  153.  
  154. #将内容更新到textedit中去
  155. content = ""
  156. for item in self.myList:
  157. content = content + "%s %s\r\n"%(item[0],item[1])
  158. self.textEdit1.setText(content)
  159. else:
  160. self.traverse_dir(tmp_path)
  161. except:
  162. self.showMsg("warning","未知错误")
  163. self.myList = []
  164.  
  165. return self.myList
  166.  
  167. def getFileVersion(self,file_name):
  168. #get the version of file
  169. try:
  170. info = win32api.GetFileVersionInfo(file_name, os.sep)
  171. ms = info['FileVersionMS']
  172. ls = info['FileVersionLS']
  173. version = '%d.%d.%d.%04d' % (win32api.HIWORD(ms), win32api.LOWORD(ms), win32api.HIWORD(ls), win32api.LOWORD(ls))
  174. print("version:",version)
  175. except:
  176. version = " "
  177.  
  178. return version
  179.  
  180. def writeToExcel(self,file_path,save_path):
  181. #file_path = self.file_path
  182. #save_path = self.save_path
  183. #write to excel
  184. print("create a workbook")
  185. book = Workbook(encoding='utf-8')#create a workbook
  186. sheet = book.add_sheet('Sheet1')#create a sheet
  187. #set style
  188. font = xlwt.Font() # 字体
  189. font.name = 'Times New Roman'
  190. font.bold = True
  191. font.underline = False
  192. font.italic = False
  193. style = xlwt.XFStyle() # 创建一个格式
  194. style.font = font # 设置格式字体
  195.  
  196. #sheet.write(0, 0, label = 'Formatted value', style) # Apply the Style to the Cell
  197. sheet.write(0, 0, "no",style)
  198. sheet.write(0, 1, "file_name",style)
  199. sheet.write(0, 2, "file_version",style)
  200. list = self.traverse_dir(file_path)
  201.  
  202. row=0
  203. num=0
  204. for item in list:
  205. row += 1
  206. num += 1
  207. print(item[0] ,item[1])
  208. sheet.write(row, 0, num, style)
  209. sheet.write(row, 1,item[0] , style)
  210. sheet.write(row, 2,item[1] , style)
  211.  
  212. book.save(save_path)
  213.  
  214. if __name__ == '__main__':
  215. app = QApplication(sys.argv)
  216. demo = GetFileVersionNo()
  217. demo.show()
  218. sys.exit(app.exec_())

python_Excel_xlwt的更多相关文章

随机推荐

  1. 解决Vue-cli3.0下scss文件编译过慢、卡顿问题

    在使用Vue-cli 3.0构建的项目中,可能存在项目编译过慢的问题,具体表现在编译时会在某一进度比如40%时停顿,等好一会儿才能够编译完成.这使得浏览器中的实时预览也会卡顿,不利于我们快速查看效果, ...

  2. 洛谷P3018 [USACO11MAR]树装饰Tree Decoration

    洛谷P3018 [USACO11MAR]树装饰Tree Decoration树形DP 因为要求最小,我们就贪心地用每个子树中的最小cost来支付就行了 #include <bits/stdc++ ...

  3. 解决vue渲染时闪烁{{}}的问题

    原文转自: 点我 Vue页面加载时v-show设置的隐藏元素出现导致页面闪烁问题在写APP社区页面的时候在一些地方用了v-show,在刷新页面的时候就发现即便在逻辑判断为false某些元素不该显示时也 ...

  4. 刷短视频看新闻看小说也能赚钱的几款APP

    一.抖音极速版 发啦! 刷短视频也能赚钱 第1步:下载[抖音极速版] 第2步:填我邀请码[831008243] 第3步:立刻提现最高[38元]红包 二.今日头条极速版 1元现金速撸 下载[今日头条极速 ...

  5. docker部署gitlab

    Docker部署gitlab 一.前提条件 (1)     存在docker (2)     服务器可以联网(外网) (3)     服务器内存至少4G(内存不够会出现502错误) 内存不足502错误 ...

  6. 深度学习环境搭建:window10+CUDA10.0+CUDNN+pytorch1.2.0

    去年底入手一台联想Y7000P,配置了Nvidia GeForce GTX 1660 Ti GPU,GPU内存6G,但是因为有GPU服务器,所以一直没有在这台笔记本上跑过模型,如今经过一番折腾,终于在 ...

  7. 【SpringBoot 基础系列】实现一个自定义配置加载器(应用篇)

    [SpringBoot 基础系列]实现一个自定义配置加载器(应用篇) Spring 中提供了@Value注解,用来绑定配置,可以实现从配置文件中,读取对应的配置并赋值给成员变量:某些时候,我们的配置可 ...

  8. 多重背包转化成完全背包 E - Charlie's Change

    http://poj.org/problem?id=1787 这个题目我一看就觉得是一个多重背包,但是呢,我不知道怎么输出路径,所以无可奈何,我就只能看一下题解了. 看了题解发现居然是把多重背包转化成 ...

  9. 模板引擎 Thymeleaf 动态渲染 HTML

    1.添加依赖 <!-- Thymeleaf 模板引擎 --> <dependency> <groupId>org.thymeleaf</groupId> ...

  10. 生产者消费者问题中的同步机制JAVA设计和实现

    目录 问题描述 问题分析 利用记录型信号量解决 运行环境 实现思路 代码实现 运行截图 过程中出现的问题和注意点 利用AND信号集解决 运行环境 实现思路 代码实现 运行截图 问题描述 若干进程通过有 ...