1.安装环境

  • 确保安装python,检查是否安装python:cmd输入python -V
  • 安装pywin32库:python3 -m install pywin32/pip3 install pywin32 -i https://douban.com/pypi
  • 使用tasklist | findstr “EXCEL.EXE”检查是否有Excel进程
  • 使用taskkill /F /IM EXCEL.EXE 终止全部Excel进程

    Excel 对象

  1. 启动 Excel
  2. 可视化
  3. 弹窗
  4. 退出

    1. >>> from win32com.client import Dispatch # 倒入win32库中的Dispatch方法
    2. >>> xlapp = Dispatch('Excel.Application') # 启动Excel
    3. >>> xlapp # 返回Excel对象
    4. <COMObject Excel.Application>
    5. >>> type(xlapp)
    6. <class 'win32com.client.CDispatch'>
    7. >>>
    8. >>> from win32com.client import DispatchEx
    9. >>> xlapp = DispatchEx('Excel.Application') # 单独起一个Excel进程
    10. >>> xlapp.Visible=True # 开启可视化
    11. >>> xlapp.Visible=False # 关闭可视化
    12. >>> xlapp.DisplayAlerts = False # 关闭弹窗
    13. >>> xlapp.Application.Quit() # 退出Excel进程

    工作簿对象

  5. 添加, add

增加add参数

  1. 打开
  2. 关闭
  3. 保存
  4. 另存为

    1. >>> wb = xlapp.Workbooks.Add() # 把创建的空白Excel表格变为有名称有显示的表格
    2. >>> wb.Count # 查看工作簿数量
    3. >>> xlapp.Workbooks.Count # 查看工作簿数量
    4. >>> wb.Close() # 把有显示的表格变为空白的表格
    5. >>> wb = xlapp.Workbooks.open(r"‪C:\Users\25569\Desktop\111.xlsx")# 打开Excel
    6. >>> wb.SaveAs(r"C:\Users\32075\OneDrive\桌面\222.xlsx")
    7. >>> wb.Worksheets.Item('Sheet1').Range('A1').value = 100 # 给sheet1,A1单元格添加内容
    8. >>> wb.Worksheets['Sheet1'].Range('A1').value = 1000 # 给sheet1,A1单元格添加内容
    9. >>> wb.Worksheets['Sheet1'].Range('A1').value = 10000

    打开一个本地文件

    1. xlapp = DispatchEx('Excel.Application') # 创建Excel进程
    2. xlapp.Visible=True # 可视化
    3. wb = xlapp.Workbooks.open(r"C:\Users\25569\Desktop\111.xlsx")# 打开本地文件

    Sheet 页对象

  5. 总数量, 及名称

  6. 获取激活的sheet页
  7. 激活sheet页
  8. 使用sheet页
  9. sheet 名称
  10. 删除sheet页
  11. 修改sheet页名
  12. 添加sheet页
    1. >>> wb.Worksheets.Count # 查找共有几个sheet页
    2. 1
    3. >>> wb.ActiveSheet # 获取当前激活的sheet页
    4. <COMObject <unknown>>
    5. >>> wb.ActiveSheet.name
    6. 'Sheet1'
    7. >>> wb.ActiveSheet.name = "test2" # 给当前激活的sheet页名称
    8. >>> ws = wb.Worksheets("Sheet1")
    9. >>> ws = wb.Worksheets["Sheet1"]
    10. >>> ws = wb.Worksheets.Item("Sheet1")
    11. >>> active
    12. _
    13. sheet = wb.ActiveSheet
    14. >>> wb.worksheets.Add(Before=sheet) # 在当前激活的sheet页前面新增一个sheet页
    15. <COMObject Add>
    16. >>> wb.Worksheets("Sheet4").Delete() # 删除指定sheet页
    17. >>> wb.Worksheets("Sheet2").Select() # 激活指定sheet页
    18. >>> wb.Sheets(1).Name # 获取指定位置的sheet页名称
    19. 'Sheet3'
    1. wb.Worksheets.Count # 查找共有几个sheet页
    2. sht = wb.Activesheet # 当前激活的sheet页
    3. sht.name # 获取激活的sheet页名称
    4. sht.name='test' # 给当前激活的sheet页改名
    5. wb.worksheets.Add(Before=sht) # 在当前激活的sheet页前面新增一个sheet页
    6. wb.Worksheets("Sheet3").Delete() # 删除某一个sheet页
    7. wb.Worksheets("Sheet2").Select() # 激活某一个sheet

    添加 sheet 页

  • self为Excel对象
  • sheet_name:新增sheet页名称,如果默认则是None

    1. def add_sheet(self, sheet_name=None):
    2. '''添加新页,页名可以自定义'''
    3. sheet = self.WorkSheets.Add()
    4. sheet.Name = sheet_name if sheet_name else sheet.Name
    5. return sheet

    获取所有 sheet 页名称

    1. def get_sheet_names(self):
    2. name_list = []
    3. a = self.Sheets.Count
    4. for i in range(1,a+1):
    5. name_list.append(self.Sheets(i).name)
    6. return sheet

    range对象

    指定区域

  • 单元格

    • 获取单元格的值
    • 设置单元格的值
    • 设置单元格颜色
    • 设置单元格字体
    • 清空单元格
  • 区域
  • 已使用区域

总行数

  • 方法一
  • 方法二

简单操作

  • 复制
  • 粘贴
  • 拷贝
  • 合并单元格
  • 筛选单元格

    1. >>> sht = wb.Worksheets("Sheet1") # 获取sheet页名称为Sheet1的sheet对象
    2. >>> sht.Cells(1,"A").value # 读取指定sheet页单元格内容
    3. >>> sht.Cells(1,1).value
    4. 111.0
    5. >>> sht.Cells(1,1).text # 读取指定单元格文本
    6. '111'
    7. >>> sht.Columns("A:A").value # 获取列内容
    8. >>> sht.Rows(1).value # 获取行内容
    9. >>> sht.Range("A1:B2").Value # 读取区域内容
    10. ((111.0, 111.0), (111.0, None))
    11. >>> sht.Range("A1:B2").Address # 获取区域地址
    12. '$A$1:$B$2'
    13. >>> sht.Rows(1).value = ["A","B"]
    14. >>> sht.Columns.Count
    15. >>> sht.Rows.Count
    16. >>> sht.UsedRange.Value # 获取已使用区域内容
    17. ((111.0, 111.0, 111.0), (111.0, None, None), (111.0, None, None))
    18. >>> sht.UsedRange.Rows.Count # 获取总行数
    19. 3
    20. >>> sht.UsedRange.Columns.Count # 获取总列数
    21. 16384
    22. >>> sht.Range("A65536").End(-4162).Row # 获取总行数
    23. 3
    24. >>> sht.Range("A1:B2")
    25. <COMObject Range>
    26. >>> sht.Range("D1").Height # 查询单元格行高
    27. >>> sht.Range("D1").Interior.ColorIndex = 3 # 给D1单元格设置颜色索引为3的颜色
    1. sht=wb.ActiveSheet # 当前激活的sheet页
    2. sht.Cells(1,1).Value # 获取单元格内容如果是数字则是1.0(1,1表示为第一行第一列)
    3. sht.Cells(1,A).text # 获取单元格文本

    通过 rgb设置单元格颜色

    1. def rgb_to_hex(rgb):
    2. '''ws.Cells(1, i).Interior.color uses bgr in hex'''
    3. bgr = (rgb[2], rgb[1], rgb[0])
    4. strValue = '%02x%02x%02x' % bgr
    5. # print(strValue)
    6. iValue = int(strValue, 16)
    7. return iValue
    8. ws.Cells(1, 1).Interior.color = rgb_to_hex((218, 36, 238))
    1. >>> sht.Range("D1").Font.Name = "宋体" # 设置单元格字体
    2. >>> sht.Range("D1").Font.Name # 获取单元格字体类型
    3. '宋体'
    4. >>> sht.Range("D1").ClearFormats() # 清除样式,恢复默认
    5. True
    6. >>> sht.Range("D1").ClearContents() # 清空内容
    7. True
    8. >>> sht.Range("D1").Clear() # 清空内容和样式
    9. True
    10. sht.Range("A1").value=1 # 给单元格赋值

    操作

  • 拷贝, 粘贴

    1. >>> sht.Range("A1:B2").Copy()
    2. True
    3. >>> sht.Range("D1").Paste
    4. >>> sht.Range("D1").PasteSpecial()
    5. True
    6. >>> sht.Range("A1:B2").Select()
  • 合并单元格

    1. # 判断是否合并单元格
    2. >>> sht.Range("A1").MergeCells
    3. False
    4. >>> sht.Range("A1:A2").Merge()
    5. >>> sht.Range("A1:A2").unMerge()

    常见用法

    1. from win32com.client import Dispatch
    2. def main(args):
    3. xlapp = Dispatch("Excel.Application")
    4. xlapp.Visible=True
    5. wb = xlapp.workbooks.open(r"C:\Users\25569\Desktop\222.xlsx") # workbooks工作簿对象
    6. # shts = wb.worksheets # worksheets sheets对象;获取所有的sheet页对象
    7. # for sht in shts:
    8. # print(sht.name)
    9. # sht = wb.Activesheet # 获取点前激活的sheet页
    10. # print(sht.name)
    11. # Range = sht.Range("A1:C3") # 获取区域的内容
    12. # print(Range.value)
    13. # row = sht.Rows(1) # 获取行内容
    14. # print(row.value)
    15. # column = sht.Columns("A") # 获取列内容
    16. # print(column.value)
    17. # cell = sht.Cells(1,1) # 获取单元格内容
    18. # print(cell.value)
    19. # cell.value="测试" # 修改单元格内容
    20. shts = wb.worksheets # worksheets sheets对象;获取所有的sheet页对象
    21. for sht in shts: # 在某个sheet页前面增加一个sheet页
    22. if sht.name == "1":
    23. new_sht = shts.Add()
    24. sht.Select()
    25. new_sht.name = "测试"
    26. break