SoFunction
Updated on 2024-11-10

Python operation Word batch contract generation implementation examples

Background: approximately 3K merchants need to reconfirm information and sign contracts. The contract is a unified Word version. Each vendor needs to change the amount section within the contract. Manual processing requires each copy and paste and the amount to generate a capitalized amount. Based on duplicate work can be lazy. Relieve it with Python.

# Import the corresponding database
import numpy as np 
import pandas as pd 
import os 
import docx
from  import Pt
from  import qn
# Modify the address of the project file
(r'C:\Users\WIN7\Desktop\Installation Bill Automation')
()

'''
Renminbi digits to uppercase Chinese characters
'''
# coding: utf-8
import warnings
from decimal import Decimal

def cncurrency(value, capital=True, prefix=False, classical=None):
  '''
  Parameters: capital: True
  capital: True Amount in uppercase Chinese characters
        False Amount in normal Chinese characters
  classical: True yuan
        False circle
  prefix: True starts with 'Renminbi'Beginning
        False, no beginning
  '''
  if not isinstance(value, (Decimal, str, int)):
    msg = '''
    Please consider using strings, or classes, due to the precision of floating point numbers.
    The author is not responsible for possible risks and damages due to errors caused by the use of floating point numbers.
    '''
    (msg, UserWarning)
  # Default uppercase amounts are in round, general Chinese character amounts are in yuan
  if classical is None:
    classical = True if capital else False
    
  # Chinese character amount prefix
  if prefix is True:
    prefix = 'Renminbi'
  else:
    prefix = ''
    
  # Kanji amount character definition
  dunit = ('Horn', 'Points')
  if capital:
    num = ('Zero', 'One', 'II', 'Three', 'Rampant', 'Woo', 'Land', 'Seven', 'Eight', 'Nine')
    iunit = [None, 'Pick up', 'Bai', 'Thousand', 'Wan', 'Pick up', 'Bai', 'Thousand','Billions', 'Pick up', 'Bai', 'Thousand', 'Wan', 'Pick up', 'Bai', 'Thousand']
  else:
    num = ('〇', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine')
    iunit = [None, 'Ten', 'Hundred', 'Thousand', 'Wan', 'Ten', 'Hundred', 'Thousand','Billions', 'Ten', 'Hundred', 'Thousand', 'Wan', 'Ten', 'Hundred', 'Thousand']
  if classical:
    iunit[0] = 'Yuan' if classical else 'Round'
  # Convert to Decimal and truncate extra decimals

  if not isinstance(value, Decimal):
    value = Decimal(value).quantize(Decimal('0.01'))

  # Handling negative numbers
  if value < 0:
    prefix += 'Negative'     # Output prefix, plus negative
    value = - value     # Take the positive portion without much consideration of rounding up or down
                # assert - value + value == 0
  # Converted to a string
  s = str(value)
  if len(s) > 19:
    raise ValueError('The amount is too large to express.')
  istr, dstr = ('.')      # Separate treatment of fractional and integer parts
  istr = istr[::-1]          # Flip the integer part of the string
  so = []   # Used to record conversion results
  
  # Zero
  if value == 0:
    return prefix + num[0] + iunit[0]
  haszero = False   # Used to mark the use of zeros
  if dstr == '00':
    haszero = True # If there is no fractional part, mark it with a zero to avoid a "rounded zero"
    
  # Handling fractional parts
  # Minutes
  if dstr[1] != '0':
    (dunit[1])
    (num[int(dstr[1])])
  else:
    ('Whole')     # If there are no points, add "whole".
  # Corner
  if dstr[0] != '0':
    (dunit[0])
    (num[int(dstr[0])])
  elif dstr[1] != '0':
    (num[0])    # No corners, no points, add "zeros" #
    haszero = True     # The markers have been added to the zeros
    
  # No integer part
  if istr == '0':
    if haszero:       # Since there is no integer part, remove the zeros in the corner positions
      ()
    (prefix)    # Add a prefix
    ()      # Flip
    return ''.join(so)

  # Handling of integer parts
  for i, n in enumerate(istr):
    n = int(n)
    if i % 4 == 0:     # In circles, millions, billions, etc., even if it's zero, there must be units #
      if i == 8 and so[-1] == iunit[4]:  # of all zeros between billions and tens of thousands
        ()            # Remove the ten thousand
      (iunit[i])
      if n == 0:             # Handle the case of zeros on these bits
        if not haszero:         # If no zeros have been added before
          (-1, num[0])    # Then add zero to the unit
          haszero = True       # The markers have been added to the zeros
      else:                # Handling non-zero cases
        (num[n])
        haszero = False         # Restart marking plus zero
    else:                  # In other locations
      if n != 0:             # Not zero
        (iunit[i])
        (num[n])
        haszero = False         # Restart marking plus zero
      else:                # of cases where processing is zero
        if not haszero:         # If no zeros have been added before
          (num[0])
          haszero = True

  # Final results
  (prefix)
  ()
  return ''.join(so)
# Data preparation phase Import capitalization
#Read prepared excel spreadsheets
text = pd.read_excel('Payment Preparation Form.xlsx')
#print(text)
text['Total EC payable']
list1 = []
for i in text['Total EC payable']:
  (cncurrency(str(i)))
(list1)
text['Capitalized amounts'] = list1
[0]
print(())
document12 = ('Staging SPM Template (12 issues).docx')
document24 = ('Staging SPM Template (24 issues).docx')
supp_num = 0 
for supp_num in range([0]):
  paragraph_num = 0
  A = [supp_num,2]
  B = [supp_num,5]
  qishu = [supp_num,3]
  supp_name = [supp_num,1]
  user_name = [supp_num,4]
  content = "bilateral recognition,up to 2020 surname Nian 3 moon 31 date,Deduction of original contract and original cooperation agreement arrival anomaly(including, but not limited to, stock-outs、out of stock、loss of goods、discrepancy in delivery)、default (on a loan or contract)、Liability、After Party A advances the relevant costs on behalf of Party B, etc.,Party A still owes Party B the total amount of payment for the goods RMB{}unit of money (in PRC: Chinese yuan, in USA: dollar, etc)(banker's anti-fraud numerals:{})。".format(A,B)
  if qishu == "12 issues":
    p = [8].clear()
    run1 = p.add_run(content)
     = Pt(12)
     = 'Imitation Song'
    (qn('w:eastAsia'), 'Imitation Song')
    ("{}.docx".format(supp_name))
  else:
    p = [8].clear()
    run1 = p.add_run(content)
     = Pt(12)
     = 'Imitation Song'
    (qn('w:eastAsia'), 'Imitation Song')
    ("{}.docx".format(supp_name))

It is divided into four main sections.
I: import the relevant packages, this is not said
Second: the amount of digital to uppercase amounts. This online a large number of ready-made function, there is no need to write their own, Copy test, OK.
Third: Prepare your own data.
Fourth: I would like to replace the content of the specified location, but found that the operation is relatively difficult, then think about amplification, direct replacement of the entire paragraph. With a format, the need to replace the contents of the direct fill in. Then use the docx package inside the .clear [clear paragraph] plus add_run [add paragraph] way, with the . and . Adjust the font size and font. Finally save on OJBK.

to this article on the Python operation Word batch contract realization example is introduced to this article, more related Python batch replace word content please search my previous posts or continue to browse the following related articles I hope you will support me in the future more!