在网上搜索的时候,经常看到两种打开方式: dispatch和EnsureDispatch

  1. import win32com.client as win32
  2. xl_dis = win32.Dispatch("Excel.Application")
  1. import win32com.client as win32
  2. xl_ens = win32.gencache.EnsureDispatch("Excel.Application")

两种方式的差别参见:

https://stackoverflow.com/questions/50127959/win32-dispatch-vs-win32-gencache-in-python-what-are-the-pros-and-cons

  1. #创建
  2. #word
  3. w = win32com.client.Dispatch("Word.Application")
  4. w = win32com.client.DispatchEx("Word.Application")#使用启动独立的进程
  5. #excel
  6. xlApp = win32com.client.Dispatch("Excel.Application")
  7. #后台运行, 不显示, 不警告
  8. w.Visible = 0;
  9. w.DisplayAlerts = 0;
  10. #打开新的文件
  11. #word
  12. doc = w.Documents.Open(FileName)
  13. #new_doc = w.Documents.Add() #创建新的文档
  14. #excel
  15. xlBook = xlApp.Workbooks.Open(FileName)
  16. #new_xlBook = xlApp.Workbooks.Add() #创建新的工作簿
  17. #插入文字
  18. #word
  19. myRange = doc.Range(0, 0)
  20. myRange.InsertBefore("hello from Python")
  21. #excel
  22. #使用样式
  23. wordStyle = myRange.Select()
  24. wordStyle.Style = constants.wdStyleHeading1
  25. #正文文字替换
  26. w.Selection.Find.ClearFormatting()
  27. w.Selection.Find.Replacement.ClearFormatting()
  28. w.Selection.Find.Execute(OldStr, False, False, False, False, False, True, 1, True, NewStr, 2)
  29. #表格操作
  30. #word
  31. doc.Tables[0].Rows[0].Cells[0].Range.Text = "hello world Python"
  32. worddoc.Tables[0].Rows.Add() #增加一行
  33. #excel
  34. #获取
  35. _sheet = xlBook.Worksheets(sheet)
  36. _sheet.Cell(row, col).Value
  37. #设置
  38. _sheet = xlBook.Worksheets(sheet)
  39. _sheet.Cells(row, col).Value = values
  40. #范围操作
  41. _sheet = xlBook.Worksheets(sheet)
  42. _sheet.Range(_sheet.Cell(row1, col1), _sheet.Cell(row2, col2)).Value
  43. #添加图片
  44. #excel
  45. _sheet = xlBook.Worksheets(sheet)
  46. _sheet.Shapes.AddPicture(picturename, 1, 1, Left, Top, Width, Height)
  47. #copy 工作簿
  48. sheets = xlBook.Worksheets
  49. sheets(1).Copy(None, sheets(1))
  50. #转换为html
  51. #word
  52. wc = win32com.client.constants
  53. w.ActiveDocument.WebOptions.RelyOnCSS = 1
  54. w.ActiveDocument.WebOptions.OptimizeForBrowser = 1
  55. w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4
  56. w.ActiveDocument.WebOptions.OrganizeInFolder = 0
  57. w.ActiveDocument.WebOptions.UseLongFileNames = 1
  58. w.ActiveDocument.WebOptions.RelyOnVML = 0
  59. w.ActiveDocument.WebOptions.AllowPNG = 1
  60. w.ActiveDocument.SaveAs(FileName, FileFormat = wc.wdFormatHTML)
  61. #打印
  62. doc.PrintOut()
  63. #保存
  64. #excel
  65. xlBook.SaveAs(FileName)#另存为
  66. xlBook.Save()
  67. #关闭
  68. #word
  69. #doc.Close()
  70. w.Documents.Close(wc.wdDoNotSaveChanges)
  71. w.Quit()
  72. #excel
  73. xlBook.Close(SaveChange = 0)
  74. xlBook.Quit()

 

 

版权声明:本文为robin2022原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/robin2022/p/16317499.html