Files
jupyter/erpnext外挂.ipynb
2025-11-09 14:53:27 +08:00

14 KiB

获取科目表信息

In [ ]:
import pymysql
db = pymysql.connect(host = "172.19.0.12",user = "songyi",password = "yylzs",database = "_5e5899d8398b5f7b" )
cursor = db.cursor()
sql = 'select account_name,account_number,parent_account from tabAccount where company= %s'
cursor.execute(sql, {'北京运动一百体育文化发展有限公司'})
data = cursor.fetchall()
for item in data:
    print(item)
print(type(data))
In [ ]:
import pymysql
db = pymysql.connect(host = "172.19.0.12",user = "songyi",password = "yylzs",database = "_5e5899d8398b5f7b" )
cursor = db.cursor()

dict1 = {}

sql = 'select account_name,account_number,parent_account from tabAccount where company= %s and parent_account is null'
cursor.execute(sql, {'北京运动一百体育文化发展有限公司'})
data = cursor.fetchall()
for item in data:
    dict1.setdefault(item[1],{})
    dict1[item[1]]['name'] = item[0]
# 获得科目分类
#print(dict1)
sql = 'select account_name,account_number,parent_account from tabAccount where company= %s and parent_account is not null and account_number is not null'
cursor.execute(sql, {'北京运动一百体育文化发展有限公司'})
data = cursor.fetchall()
dict2 = {}
for k, v in dict1.items():
    for item in data:
        parent = item[2].split(' - ')[0]
        if parent == k:
            dict2.setdefault(item[1],{})
            dict2[item[1]]['name'] = item[0]
# 获得科目明细
dict3 = {}

for item in data:
    parent = item[2].split(' - ')[0]
    if len(item[1]) == 4 and parent in dict2.keys():
        dict3.setdefault(item[1],{})
        dict3[item[1]]['name'] = item[0]
        dict3[item[1]]['category'] = dict2[parent]['name']
        dict3[item[1]]['level'] = 1
        dict3[item[1]]['parent'] = ''
for item in data:
    parent = item[2].split(' - ')[0]
    if len(item[1]) == 6 and parent in dict3.keys():
        dict3.setdefault(item[1],{})
        dict3[item[1]]['name'] = item[0]
        dict3[item[1]]['category'] = dict3[parent]['category']
        dict3[item[1]]['level'] = 2
        dict3[item[1]]['parent'] = parent        
for item in data:
    parent = item[2].split(' - ')[0]
    if len(item[1]) == 8 and parent in dict3.keys():
        dict3.setdefault(item[1],{})
        dict3[item[1]]['name'] = item[0]
        dict3[item[1]]['category'] = dict3[parent]['category']
        dict3[item[1]]['level'] = 3
        dict3[item[1]]['parent'] = parent          
    
for k, v in dict3.items():
    print(k,v['name'],v['category'],v['level'],v['parent'])

获取结账余额表

In [ ]:
import pymysql
db = pymysql.connect(host = "172.19.0.12",user = "songyi",password = "yylzs",database = "_5e5899d8398b5f7b" )
cursor = db.cursor()

dict1 = {}

sql = 'select account,debit,credit,period_closing_voucher from `tabAccount Closing Balance` where company= %s and closing_date = %s'
cursor.execute(sql, ('北京运动一百体育文化发展有限公司','2023-03-31'))
data = cursor.fetchall()
for item in data:
    print(item)

获取关账凭证信息

In [ ]:
import pymysql
from pymysql import converters, FIELD_TYPE

conv = converters.conversions
conv[FIELD_TYPE.NEWDECIMAL] = float
conv[FIELD_TYPE.DATE] = str
db = pymysql.connect(host = "172.19.0.12",user = "songyi",password = "yylzs",database = "_5e5899d8398b5f7b" )
cursor = db.cursor()

dict1 = {}

sql = 'select name,transaction_date,remarks from `tabPeriod Closing Voucher` where company= %s and docstatus = %s'
cursor.execute(sql, ('北京运动一百体育文化发展有限公司',1))
data = cursor.fetchall()
for item in data:
    print(item)

获取凭证

In [ ]:
import pymysql
db = pymysql.connect(host = "172.19.0.12",user = "songyi",password = "yylzs",database = "_5e5899d8398b5f7b" )
cursor = db.cursor()


sql = 'select name,title,total_debit,total_credit from `tabJournal Entry` where company= %s and docstatus = %s'
cursor.execute(sql, ('北京运动一百体育文化发展有限公司',1))
data = cursor.fetchall()
for item in data:
    print(item)

获取分录

In [ ]:
import pymysql
from pymysql import converters, FIELD_TYPE

conv = converters.conversions
conv[FIELD_TYPE.NEWDECIMAL] = float
conv[FIELD_TYPE.DATE] = str
db = pymysql.connect(host = "172.19.0.10",user = "songyi",password = "yylzs",database = "_5e5899d8398b5f7b" )
cursor = db.cursor()


sql = 'select parent,account,debit,credit,against_account from `tabJournal Entry Account` where docstatus = %s and parent = %s'
cursor.execute(sql, (1,'ACC-JV-2025-00099'))
data = cursor.fetchall()
for item in data:
    print(item)

获取总账

In [ ]:
import pymysql
from pymysql import converters, FIELD_TYPE

conv = converters.conversions
conv[FIELD_TYPE.NEWDECIMAL] = float
db = pymysql.connect(host = "172.19.0.10",user = "songyi",password = "yylzs",database = "_5e5899d8398b5f7b" )
cursor = db.cursor()


sql = 'select name,account,against,voucher_no,debit,credit from `tabGL Entry` where fiscal_year = %s'
cursor.execute(sql, ('2025'))
data = cursor.fetchall()
for item in data:
    print(item)
In [ ]:
import pymysql
from pymysql import converters, FIELD_TYPE

conv = converters.conversions
conv[FIELD_TYPE.NEWDECIMAL] = float
db = pymysql.connect(host = "172.19.0.10",user = "songyi",password = "yylzs",database = "_5e5899d8398b5f7b" )
cursor = db.cursor()


sql = 'select name,account,against,voucher_no,debit,credit from `tabGL Entry` where fiscal_year = %s and voucher_no = %s'
cursor.execute(sql, ('2025','ACC-PCV-2025-00010'))
data = cursor.fetchall()
for item in data:
    print(item)

使用模板生成凭证

In [ ]:
import pymysql
from pymysql import converters, FIELD_TYPE
import openpyxl
from docxtpl import DocxTemplate,InlineImage

def num_to_rmb(num):
    # 定义中文数字和单位
    digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
    units = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟']
    dec_units = ['角', '分']
    # 分离整数和小数部分
    integer_part = int(num)
    decimal_part = round((num - integer_part) * 100)  # 保留两位小数
    # 处理整数部分
    if integer_part == 0:
        result = '零元'
    else:
        integer_str = str(integer_part)
        result = ''
        zero_flag = False  # 标记是否需要添加零
        
        for i in range(len(integer_str)):
            digit = int(integer_str[i])
            pos = len(integer_str) - i - 1  # 当前位置的权值
            
            if digit == 0:
                zero_flag = True
            else:
                if zero_flag:
                    result += '零'
                    zero_flag = False
                result += digits[digit] + units[pos]
        
        result += '元'    
    # 处理小数部分
    if decimal_part == 0:
        result += '整'
    else:
        jiao = decimal_part // 10
        fen = decimal_part % 10
        
        if jiao > 0:
            result += digits[jiao] + dec_units[0]
        elif integer_part > 0:
            result += '零'
            
        if fen > 0:
            result += digits[fen] + dec_units[1]    
    # 特殊情况:"壹拾"开头的处理
    if result.startswith('壹拾'):
        result = result[1:]    
    return '人民币' + result

conv = converters.conversions
conv[FIELD_TYPE.NEWDECIMAL] = float
db = pymysql.connect(host = "172.19.0.10",user = "songyi",password = "yylzs",database = "_5e5899d8398b5f7b" )
cursor = db.cursor()

list1 = []
tpl = DocxTemplate("data/tpl_pingzheng.docx")
sql = 'select parent,account,debit,credit,against_account from `tabJournal Entry Account` where docstatus = %s and parent = %s'
cursor.execute(sql, (1,'ACC-JV-2025-00002-1'))
data = cursor.fetchall()
sum_debit = 0.00
sum_credit = 0.00
for item in data:
    dict1 = {}
    dict1['zhaiyao'] = item[0]
    dict1['kemu'] = item[1]
    if item[2] == 0.0:
        dict1['debit'] = ''        
    else:
        dict1['debit'] = '{:.2f}'.format(item[2])
        sum_debit+= item[2]
    if item[3] == 0.0:
        dict1['credit'] = ''        
    else:
        dict1['credit'] = '{:.2f}'.format(item[3])
        sum_credit+= item[3]
    list1.append(dict1)    


context = {}
context['fenlu'] = list1
context['sum_debit'] = '{:.2f}'.format(sum_debit)
context['sum_credit'] = '{:.2f}'.format(sum_credit)
tpl.render(context)
tpl.save('data/test1.docx')

连接postgresql

In [11]:
import psycopg2

# 建立数据库连接
conn = psycopg2.connect(
database="directus",
user="mydata",
password="songyi",
host="127.0.0.1",
port="5432"
)
cur = conn.cursor()
cur.execute("SELECT person ->'name' as name FROM tice_event")
rows = cur.fetchall()
print(rows)
conn.close()
[(None,)]
In [ ]: