[Python] python在windows下操作word的方法 →→→→→进入此内容的聊天室

来自 , 2019-04-19, 写在 Python, 查看 121 次.
URL http://www.code666.cn/view/d5ade38a
  1. import win32com
  2. from win32com.client import Dispatch, constants
  3.  
  4. w = win32com.client.Dispatch('Word.Application')
  5. # 或者使用下面的方法,使用启动独立的进程:
  6. # w = win32com.client.DispatchEx('Word.Application')
  7.  
  8. # 后台运行,不显示,不警告
  9. w.Visible = 0
  10. w.DisplayAlerts = 0
  11.  
  12. # 打开新的文件
  13. doc = w.Documents.Open( FileName = filenamein )
  14. # worddoc = w.Documents.Add() # 创建新的文档
  15.  
  16. # 插入文字
  17. myRange = doc.Range(0,0)
  18. myRange.InsertBefore('Hello from Python!')
  19.  
  20. # 使用样式
  21. wordSel = myRange.Select()
  22. wordSel.Style = constants.wdStyleHeading1
  23.  
  24. # 正文文字替换
  25. w.Selection.Find.ClearFormatting()
  26. w.Selection.Find.Replacement.ClearFormatting()
  27. w.Selection.Find.Execute(OldStr, False, False, False, False, False, True, 1, True, NewStr, 2)
  28.  
  29. # 页眉文字替换
  30. w.ActiveDocument.Sections[0].Headers[0].Range.Find.ClearFormatting()
  31. w.ActiveDocument.Sections[0].Headers[0].Range.Find.Replacement.ClearFormatting()
  32. w.ActiveDocument.Sections[0].Headers[0].Range.Find.Execute(OldStr, False, False, False, False, False, True, 1, False, NewStr, 2)
  33.  
  34. # 表格操作
  35. doc.Tables[0].Rows[0].Cells[0].Range.Text ='123123'
  36. worddoc.Tables[0].Rows.Add() # 增加一行
  37.  
  38. # 转换为html
  39. wc = win32com.client.constants
  40. w.ActiveDocument.WebOptions.RelyOnCSS = 1
  41. w.ActiveDocument.WebOptions.OptimizeForBrowser = 1
  42. w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4
  43. w.ActiveDocument.WebOptions.OrganizeInFolder = 0
  44. w.ActiveDocument.WebOptions.UseLongFileNames = 1
  45. w.ActiveDocument.WebOptions.RelyOnVML = 0
  46. w.ActiveDocument.WebOptions.AllowPNG = 1
  47. w.ActiveDocument.SaveAs( FileName = filenameout, FileFormat = wc.wdFormatHTML )
  48.  
  49. # 打印
  50. doc.PrintOut()
  51.  
  52. # 关闭
  53. # doc.Close()
  54. w.Documents.Close(wc.wdDoNotSaveChanges)
  55. w.Quit()
  56. #//python/8255

回复 "python在windows下操作word的方法"

这儿你可以回复上面这条便签

captcha