win32com.client:AttributeError:wdHeaderFooterPrimary和AttributeError:wdAlignParagraphCenter

4 投票
1 回答
6181 浏览
提问于 2025-04-18 14:51

我们准备了一个Python脚本,用来在Word表格中显示图片。

import matplotlib.pyplot as plt
import pylab 
import win32com.client as win32  
import os

# Skip picture making parts

#Generate word file
#Create and formating
wordapp = win32.Dispatch("Word.Application") #create a word application object

wordapp.Visible = 1 # hide the word application

doc=wordapp.Documents.Add() 

# create a new application

doc.PageSetup.RightMargin = 20

doc.PageSetup.LeftMargin = 20

doc.PageSetup.Orientation = 1

# a4 paper size: 595x842

doc.PageSetup.PageWidth = 595
doc.PageSetup.PageHeight = 842

header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range

header_range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter

header_range.Font.Bold = True

header_range.Font.Size = 12

header_range.Text = ""
#Create and formating

#insert table
total_column = 3
total_row = len(compound_name)+1
rng = doc.Range(0,0)
rng.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter
table = doc.Tables.Add(rng,total_row, total_column)
table.Borders.Enable = True
if total_column > 1:
    table.Columns.DistributeWidth()
#table title
table.Cell(1,1).Range.InsertAfter("title1")
table.Cell(1,2).Range.InsertAfter("title2")
table.Cell(1,3).Range.InsertAfter("title3")
#collect image
frame_max_width= 167 # the maximum width of a picture
frame_max_height= 125 # the maximum height of a picture
#
for index, filename in enumerate(filenames): # loop through all the files and folders for adding pictures
 if os.path.isfile(os.path.join(os.path.abspath("."), filename)): # check whether the current object is a file or not
      if filename[len(filename)-3: len(filename)].upper() == 'PNG': # check whether the current object is a JPG file


                    cell_column= index % total_column + 1
                    cell_row = index / total_column + 2


                    cell_range= table.Cell(cell_row, cell_column).Range
                    cell_range.ParagraphFormat.LineSpacingRule = win32.constants.wdLineSpaceSingle
                    cell_range.ParagraphFormat.SpaceBefore = 0 
                    cell_range.ParagraphFormat.SpaceAfter = 3

        #this is where we are going to insert the images
                    current_pic = cell_range.InlineShapes.AddPicture(os.path.join(os.path.abspath("."), filename))


doc.SaveAs(os.path.join(os.path.abspath("."),"final.doc"))
doc.Close()

但是,当运行这个脚本时,会因为这一行代码出现错误:

 header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range

这是错误信息:

Traceback (most recent call last):
  File "Drawing.py", line 99, in <module>
  header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range
  File "C:\Python27\Lib\site-packages\win32com\client\__init__.py", line 170, in __getattr__
   raise AttributeError(a)
  AttributeError: wdHeaderFooterPrimary

我觉得“wdHeaderFooterPrimary”这部分可能有问题。所以我把后面的几行代码注释掉,然后再运行。

#header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range

#header_range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter

#header_range.Font.Bold = True

#header_range.Font.Size = 12

#header_range.Text = ""

结果又出现了另一个错误信息:

Traceback (most recent call last):
  File "C:Drawing.py", line 114, in <module>
    rng.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter
  File "C:\Python27\Lib\site-packages\win32com\client\__init__.py", line 170, in __getattr__
    raise AttributeError(a)
AttributeError: wdAlignParagraphCenter

我在64位的Windows 7上运行的是Python 2.7.6。matplotlib.pyplot和pylab已经安装好了。win32com.client是32位的2.7.6版本,构建号是219。Office是64位的,但下载网站的说明说32位的win32在64位的Office和Windows 7上应该能正常工作(http://sourceforge.net/projects/pywin32/?source=navbar)。请问有没有高手能给点建议或解决方案?谢谢!

1 个回答

5

这些常量只有在可以使用静态调度的时候才能用。要做到这一点,你需要使用 EnsureDispatch(而不是 Dispatch),或者通过 makepy.py 或 genclient 来生成类型库(这正是 EnsureDispatch 为你做的事情)。所以我建议你试试使用 EnsureDispatch。注意:它在 win32com.client.gencache 里:

xl = win32com.client.gencache.EnsureDispatch ("Word.Application")

撰写回答