【问题标题】:How to fill word table template in excel using python如何使用python在excel中填写单词表模板
【发布时间】:2019-12-19 21:59:38
【问题描述】:

You can find my Excel data here :, and

My template is looking like this....

我在表格中有 Word 文档,我需要使用 Excel 文件中的数据填充表格。

我试过了,但是我没有得到任何与 python 代码相关的帮助。

[import xlrd
loc=('D:/SAIKUMAR/TEMPLATE/Dynamic_Reporting_Excel_Input.xlsx')
file=xlrd.open_workbook(loc,on_demand=True  )
sheet=file.sheet_by_index(0)
print("First row index: ",sheet.cell_value(0,0))#index for first columns 
print("no.of rows:",sheet.nrows)# count the number of rows
print("no of columns:",sheet.ncols)
for i in range(0,sheet.ncols):# print which row data you want 
    print(sheet.cell_value(0,i))
print('____________________')
for i in range(sheet.nrows): # print which column data you want 
    print(sheet.cell_value(i,6))

print(sheet.row_values(1))    

#arrayofvalues = sheet.col_values(columnindex)
arrayofvalues = sheet.col_values(6)

print(arrayofvalues)


########################################################
from docx.api import Document

# Load the first table from your document. In your example file,
# there is only one table, so I just grab the first one.
document = Document('Dynamic_Reporting_Word_Template.docx')
table = document.tables\[1\]
#print(table)
# Data will be a list of rows represented as dictionaries
# containing each row's data.
data = \[\]
keys = None
for i, row in enumerate(table.rows):
    text=(cell.text for cell in row.cells)
    if i==0:
        keys=tuple(text)
        continue
    row_data=dict(zip(keys, text))
    data.append(row_data)][1]

这是我的模板,我用图片给出的,实际上它是存储在 word 文档中的。

【问题讨论】:

  • 如果您在 xlsx 中有它,您可以将其转换为 .csv 之后,您可以轻松找到样板脚本来使用 .csv 值填充 excel 单元格。您可能会发现这很有帮助。 pbpython.com/python-word-template.html
  • 但我的模板看起来不像,它看起来像表格
  • 你是说 MS Word 表格?
  • 是的,您可以在上面的附加链接中找到我的表格
  • 你可以找到这个帮助 -- stackoverflow.com/questions/10366596/…

标签: python-3.x vba templates ms-word


【解决方案1】:

在 VBA 编辑器中,我使用 Tools > References 菜单选项添加对 Microsoft Excel 12.0 Object Library 的引用。

在 VBA 模块的顶部,我添加了以下声明以使用 1 而不是 0 作为数组的起始索引。 (这不是完全必要的,但它与我的示例代码有关。)

Option Base 1

这是我的主要过程的示例代码:

Sub TestLoadingExcelData()
    Const TemplatePath = "C:\Users\Rupert\AppData\Roaming\Microsoft\Templates\New_LPD.dotm"
    Const SpreadsheetPath = "D:\Rupert\Documents\MyTimeLine.xlsx"
    Const targetPath = "D:\Rupert\Documents\tmp\"

    Const SheetName = "Sheet1"
    Const NumberOfCols = 12
    Const StartingRow = 2
    Const MaxRows = 500
    Dim TwoDimArray(MaxRows, NumberOfCols) As String
    Dim i As Long, j As Long
    Dim tmpText As String

    Call LoadDataFromOneSheet(SpreadsheetPath, SheetName, NumberOfCols, StartingRow, TwoDimArray, MaxRows)

    'Type the text from the array.
    For i = StartingRow To MaxRows
        If TwoDimArray(i, 1) = "" Then Exit For
        Documents.Add Template:=TemplatePath, NewTemplate:=False, DocumentType:=0

        'Go to the starting point to write text in the template. I'm using some text that I happened to have in my template.
            Selection.Find.ClearFormatting
        With Selection.Find
            .Text = "This is the built-in Heading 2."
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        Selection.Find.Execute
        'Delete the placeholder text.
        Selection.Delete

        For j = 1 To NumberOfCols
            tmpText = TwoDimArray(i, j)
            If j = 1 Then
                Selection.TypeText Text:=tmpText & vbCr
            ElseIf tmpText <> "" Then
                Selection.TypeText Text:="---" & tmpText & vbCr
            End If
        Next j
        ActiveDocument.SaveAs FileName:="""" & targetPath & TwoDimArray(i, 1) & ".docx"""
        ActiveDocument.Close
    Next i

End Sub

这是我从 Excel 加载数组的过程的示例代码。为此,我使用了一个单独的过程来隔离 Excel 应用程序中可能出现的错误。

Private Sub LoadDataFromOneSheet(fSpreadsheetPath, fSheetName, fNumberOfCols, fStartingRow, ByRef fTwoDimArray, fMaxRows)

    On Error GoTo ErrorHandler
    Dim tmpText As String
    Dim i As Long, j As Long, emptyRowCount As Long

    Dim wbXL
    Set wbXL = CreateObject("excel.application")
    wbXL.Workbooks.Open FileName:=fSpreadsheetPath
    Dim MyWorksheet

    For Each MyWorksheet In wbXL.Worksheets
        If Trim(MyWorksheet.Name) = fSheetName Then
            For i = fStartingRow To fMaxRows
                If SmartRTrim(CStr(MyWorksheet.Cells(i, 1).Value)) = "" Then
                    'Quit when you reach an empty cell in the first column.
                    Exit For
                Else
                    For j = 1 To fNumberOfCols
                        fTwoDimArray(i, j) = SmartRTrim(CStr(MyWorksheet.Cells(i, j).Value))
                    Next j
                End If
            Next i
        End If
    Next MyWorksheet

    wbXL.Workbooks(1).Close
    wbXL.Quit
    Set wbXL = Nothing
Exit Sub
' Error-handling routine.
ErrorHandler:
    wbXL.Quit
    Set wbXL = Nothing
    MsgBox SpreadsheetPath & vbCr & Err.Description
End Sub

这是我用来从 Excel 单元格文本中修剪无关控制字符的函数:

Public Function SmartRTrim(fstring) As String
    'Remove control characters and spaces from the end of the string.
    Dim tmpString As String
    Dim i As Integer

    tmpString = fstring
    For i = 1 To 300
        If tmpString = "" Then
            Exit For
        Else
            If Asc(Right(tmpString, 1)) < 30 Or Right(tmpString, 1) = " " Then
                tmpString = Left(tmpString, Len(tmpString) - 1)
            Else
                Exit For
            End If
        End If
    Next i
    SmartRTrim = RTrim(tmpString)
End Function

这段代码应该让您大致了解我如何将数据从 excel 获取到 word 模板。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-04
    • 2019-02-26
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    相关资源
    最近更新 更多