2013-04-16 1 views
1

Я пытаюсь обновить таблицу microsoft word - 2010, удалив ее содержимое (кроме первого содержимого строки) с помощью клиентского компонента python и win32com. Я даже посмотрел на библиотеку MSDN (http://msdn.microsoft.com/en-us/library/bb244515.aspx) и обнаружил, что Delete может помочь мне в этом, что-то вроде этого. (не также имел взгляд @How to read contents of an Table in MS-Word file Using Python?)Python - невозможно редактировать содержимое таблицы в Microsoft Word с помощью win32com

..///

# delete row 1 of table 1 
doc.Tables(1).Rows(1).Delete 
# delete cell 1,1 of table 1 
doc.Tables(1).Cell(1, 1).Delete 

..///

но делать эти шаги, строка таблицы не удаляются (ни ячейка [1,1] удаляется). Есть что-то, что мне не хватает? Любые предложения приветствуются.

функция Python для очистки содержимого таблицы наклеен здесь со

..//

def updateTable(name): 

    #tell word to open the document 
    word.Documents.Open (IP_Directory_Dest + "\\" + name) 

    #open it internally (i guess...) 
    doc = word.Documents(1) 

## doc.Content.Text = "This is the string to add to the document." 
## doc.Content.MoveEnd() 

## doc.Content.Select 
## doc.Tables(1).Rows(2).Select 
## Selection.InsertRowsBelow 

## doc.Tables [1]. Rows [1]. Cells [1]. Range.Text = '123123 ' 
## doc.Tables [1]. Rows.Add() # add a line 

    # specifically select TABLE # 1 
    table = doc.Tables(1) 
    # count the number of rows in TABLE # 1 
    numRows = table.Rows.Count 

    # count number of columns 
    numCols = table.Columns.Count 

    print ('Number of Rows in TABLE',numRows) 
    print ('Number of Columns in TABLE',numCols) 

    # print the row 1 of TABLE # 1 -- for checking 
    print ('### 1 - CHECK this ONE ... ',table.Rows(1).Range.Text) 

    # delete row 1 of table 1 
    doc.Tables(1).Rows(1).Delete 
    # delete cell 1,1 of table 1 
    doc.Tables(1).Cell(1, 1).Delete 

    # again count the number of rows in table 
    numRows = table.Rows.Count 

    print numRows 

    # print the row 1 of TABLE # 1 -- after Deleting the first ROW --> for checking 
    print ('### 2 - CHECK this ONE ... ',table.Rows(1).Range.Text) 

    # get the number of tables 
    numberTables = doc.Tables.Count 
    # count the number of tables in document 
    print numberTables 

    #delete ALL tables 
    tables = doc.Tables 
    for table in tables: 
     # to get the content of Row # 1, Column # 1 of table 
     print table.Cell(Row =1, Column = 1).Range.Text 
##  table.Delete(Row =2) 
     # this one deletes the whole table (which is not needed) 
     #table.Delete() 

    #re-save in IP folder 
    doc.SaveAs(IP_Directory_Dest + "\\" + name) 

    #close the stream 
    doc.Close() 

... ///

игнорируйте закомментированные секции (я был пытаясь сделать работу)

ответ

0

Добавить пустые круглые скобки в конце строки:

doc.Tables(1).Rows(1).Delete() 

Эти круглые скобки необходимы для вызова метода.

+0

спасибо Дэвид. Это действительно помогло удалить строку 1 таблицы 1. Однако любое предложение о том, как очистить содержимое таблицы (сохраняя формат таблицы как есть), а не удалять строку как таковую. Благодарю. – Varun

+0

@Varun: Что происходит, когда вы удаляете эту строку и просто выполняете строку 'doc.Tables (1) .Cell (1, 1) .Delete()'? –

+0

Дэвид, он удаляет только ячейку (1,1) таблицы 1. – Varun

0

Все,

Так вот что я выяснил. Я собираюсь поделиться кодом, который я написал, чтобы исправить это.

Выполняя это, я узнал, как очистить содержимое таблицы (конкретная строка и столбец), как добавить строку, получить количество столбцов и строк в таблице слов и др. Также я понял, что, поскольку в API, используемом для python/win32 (за исключением библиотеки MSDN), имеется мало документации, единственный способ, который, как я думал, привык к этим API, - понять код VB (в основном его настоящее @ MSDN http://msdn.microsoft.com/en-us/library/bb244515.aspx) и попробуйте сделать соответствующий аналогичный код для python-win32 тоже. Это мое понимание.

..///

######################## 
# 
# Purpose : To update the Table contents present in file 
#  @ name  : name of the document to process. 
#  @ tableCount : Specific Table number to edit. 
# 
####################### 

def updateTable(name,tableCount): 

    #tell word to open the document 
    word.Documents.Open (IP_Directory_Dest + "\\" + name) 

    #open it internally 
    doc = word.Documents(1) 

    # answer to Question # 2 (how to update a specific cell in a TABLE) 
    # clearing Table # 1, Row # 1, cell # 1 content 
    doc.Tables (1). Rows (1). Cells (1). Range.Text = '' 

    #Clearing Table # 1, Row # 1, Col # 4 content to blank 
    doc.Tables (1). Cell(1, 4). Range.Text = '' 

    # specifically select TABLE # tableCount 
    table = doc.Tables(tableCount) 
    # count the number of rows in TABLE # 1 
    numRows = table.Rows.Count 

    # count number of columns 
    numCols = table.Columns.Count 

    print ('Number of Rows in TABLE',numRows) 
    print ('Number of Columns in TABLE',numCols) 


    # NOTE : ROW # 1 WILL NOT BE DELETED, AS IT IS COMMON FOR BOTH IP AND IR 
    # delete and add the same number of rows 
    for row in range(numRows): 
     # add a row at the end of table 
     doc.Tables(tableCount).Rows.Add() 
     # delete row 2 of table (so as to make the effect of adding rows equal) 
     doc.Tables(tableCount).Rows(2).Delete() 


    #re-save in IP folder 
    doc.SaveAs(IP_Directory_Dest + "\\" + name) 

    #close the stream 
    doc.Close() 

..///