win32com模块

import win32com.client as win32

建立一个可视的excel

app = 'Excel'
xl = win32.gencache.EnsureDispatch('%s.Application' % app)
ss = xl.Workbooks.Add()
sh = ss.ActiveSheet
"""
0代表隐藏对象,但可以通过菜单再显示
-1代表显示对象
2代表隐藏对象,但不可以通过菜单显示,只能通过VBA修改为显示状态
 """
 xl.Visible = True

编辑excel

sh.Cells(1,1).Value =1             #A1赋值为1
sh.Cells(1,1).Font.Bold = True     #加粗
sh.Range(sh.Cells(1, 1),sh.Cells(1,5)).Font.Name = "Times New Roman"#选择指定区域
sh.Range(sh.Cells(1, 1), sh.Cells(1,5)).Font.Size = 10.5
sh.Cells(row, col).Name = "Arial"#字体类型
sh.Rows(row).Delete()#删除行  
sh.Columns(row).Delete()#删除列

sh.Range(sh.Cells(1,1),sh.Cells(1,1)).HorizontalAlignment = 
win32.constants.xlCenter #水平居中xlCenter

sh.SaveAs(path+'demo.xls')
ss.Close(False)
xl.Application.Quit()
from win32com.client import Dispatch    
import win32com.client    
class easyExcel:     
      def __init__(self, filename=None):  #打开文件或者新建文件(如果不存在的话)  
          self.xlApp = win32com.client.Dispatch('Excel.Application')    
          if filename:    
              self.filename = filename    
              self.xlBook = self.xlApp.Workbooks.Open(filename)    
          else:    
              self.xlBook = self.xlApp.Workbooks.Add()    
              self.filename = ''  
        
      def save(self, newfilename=None):  #保存文件  
          if newfilename:    
              self.filename = newfilename    
              self.xlBook.SaveAs(newfilename)    
          else:    
              self.xlBook.Save()        
      def close(self):  #关闭文件  
          self.xlBook.Close(SaveChanges=0)    
          del self.xlApp    
      def getCell(self, sheet, row, col):  #获取单元格的数据  
          sht = self.xlBook.Worksheets(sheet)    
          return sht.Cells(row, col).Value    
      def setCell(self, sheet, row, col, value):  #设置单元格的数据    
          sht = self.xlBook.Worksheets(sheet)    
          sht.Cells(row, col).Value = value  
      def setCellformat(self, sheet, row, col):  #设置单元格的数据样式
          sht = self.xlBook.Worksheets(sheet)    
          sht.Cells(row, col).Font.Size = 15#字体大小  
          sht.Cells(row, col).Font.Bold = True#是否黑体  
          sht.Cells(row, col).Name = "Arial"#字体类型  
          sht.Cells(row, col).Interior.ColorIndex = 3#表格背景  
          #sht.Range("A1").Borders.LineStyle = xlDouble  
          sht.Cells(row, col).BorderAround(1,4)#表格边框  
          sht.Rows(3).RowHeight = 30#行高  
          sht.Cells(row, col).HorizontalAlignment = -4131 #水平居中xlCenter  
          sht.Cells(row, col).VerticalAlignment = -4160 #  
      def deleteRow(self, sheet, row):  
          sht = self.xlBook.Worksheets(sheet)  
          sht.Rows(row).Delete()#删除行  
          sht.Columns(row).Delete()#删除列
      def getRange(self, sheet, row1, col1, row2, col2):  #获得一块区域的数据,返回为一个二维元组    
          sht = self.xlBook.Worksheets(sheet)  
          return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Value    
      def addPicture(self, sheet, pictureName, Left, Top, Width, Height):  #插入图片    
          sht = self.xlBook.Worksheets(sheet)    
          sht.Shapes.AddPicture(pictureName, 1, 1, Left, Top, Width, Height)    
                
      def cpSheet(self, before):  #复制工作表  
          shts = self.xlBook.Worksheets    
          shts(1).Copy(None,shts(1))

      def inserRow(self,sheet,row): #插入一个工作表
          sht = self.xlBook.Worksheets(sheet)
          sht.Rows(row).Insert(1)

      #下面是一些测试代码。
if __name__ == "__main__":    
      #PNFILE = r'c:/screenshot.bmp'  
      xls = easyExcel(r'd:\jason.li\Desktop\empty_book.xlsx')     
      #xls.addPicture('Sheet1', PNFILE, 20,20,1000,1000)    
      #xls.cpSheet('Sheet1')  
      xls.setCell('sheet1',2,'A',88)  
      row=1  
      col=1  
      print("*******beginsetCellformat********")  
      # while(row<5):
      #   while(col<5):
      #       xls.setCellformat('sheet1',row,col)
      #       col += 1
      #       print("row=%s,col=%s" %(row,col))
      #   row += 1
      #   col=1
      #   print("*******row********")
      # print("*******endsetCellformat********")
      # print("*******deleteRow********")
      # xls.deleteRow('sheet1',5)
      xls.inserRow('sheet1',7)
      xls.save()    
      xls.close()
from win32com.client import Dispatch
import win32com.client
import time

# 获取excel 对象

excel = win32com.client.Dispatch('Excel.Application')

"""
0代表隐藏对象,但可以通过菜单再显示
-1代表显示对象
2代表隐藏对象,但不可以通过菜单显示,只能通过VBA修改为显示状态
"""
excel.Visible = -1

# 打开excel

myBook = excel.Workbooks.Open("e:/接口测试用例.xlsx")

# sheet页,可以是序号,也可以是名称
mySheet = myBook.Worksheets("过程结果")
#excel的下标都是从1开始的
#mySheet = myBook.Worksheets(1)

time.sleep(2)

# 删除行,清除历史数据
mySheet.Rows("2:500").delete
#mySheet.Columns("1").delete

# 获取当前sheet页有效的行数
LastRow = mySheet.usedrange.rows.count
print("该sheet页目前已经存在", LastRow, "行")

# 获取当前sheet页有效的列数
LastColumn = mySheet.usedrange.columns.count
print(LastColumn)

# 焦点转移到sheet页
mySheet.Activate
# 给单元格赋值 Cells(行,列)
mySheet.Cells(2, 2).Value = "使用win32com"
# 设置单元格字体位红色
mySheet.Cells(2, 2).Font.Color = -16776961
# 设置单元格字体为粗体
mySheet.Cells(2, 2).Font.Bold = True
# 设置单元格字体
mySheet.Cells(2, 2).Font.Name = "微软雅黑"

time.sleep(1)

mySheet.Activate
mySheet.Cells(2, 3).Value = "使用win32com"
# 设置单元格字体位绿色
mySheet.Cells(2, 3).Font.Color = -11489280
mySheet.Cells(2, 3).Font.Bold = True

# 获取一个单元格的值
aCellValue=mySheet.Cells(2, 3).Value
print(aCellValue)


# 获取一个范围的值,类型为嵌套的list
range_list=mySheet.Range(mySheet.Cells(1, 1), mySheet.Cells(5, 5)).Value

# 给一个范围赋值,输入的值应该为嵌套的list
mySheet.Range(mySheet.Cells(6, 1), mySheet.Cells(10, 10)).Value = range_list
# 改变一个范围的属性值
mySheet.Range(mySheet.Cells(6, 1), mySheet.Cells(10, 10)).Font.Color = -11489280

# 如果范围是一行的话,赋值应该使用非嵌套的list,例如:
row_v=(1,2,3,4)
mySheet.Range(mySheet.Cells(11, 1), mySheet.Cells(11, 4)).Value = row_v

# 给整个一行赋值,慎用。。。
mySheet.Rows(12).Value = row_v
print(range_list)

#单元格添加颜色
WinSheet.Cells(1, 1).Interior.ColorIndex = 3
#或者Range("A1") 
WinSheet.Range("A1").Interior.ColorIndex = 3   
#3=红色,不同的值代表不同的颜色,可以去查看msdn  vba 文档,这就不详细说了
 
#再是RGB调色方式#Cells 和 Range都可以,Range可以选择一大片区域
WinSheet.Cells(1, 1).Interior.Color = RGB(0, 0, 255) 
#或
WinSheet.Range("A1").Interior.Color = RGB(255, 0, 255) 
#字体的颜色也是一样
WinSheet.Cells(1, 1).Font.ColorIndex = 3
WinSheet.Cells(1, 1).Font.Color = RGB(0, 0, 255)

# 保存
myBook.save

# 退出
myBook.close

猜你喜欢

转载自blog.csdn.net/u013289615/article/details/89295957
今日推荐