zoukankan      html  css  js  c++  java
  • 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)

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