import win32com.client
import xml.etree.ElementTree as ET
def connect_to_quickbooks():
"""Establishes a connection to QuickBooks Desktop."""
try:
qb = win32com.client.Dispatch("QBXMLRP2.RequestProcessor")
qb.OpenConnection("", "QBXML Test App")
qb.BeginSession("", 2) # 2 = qbFileOpenDoNotCare
return qb
except Exception as e:
print("Error connecting to QuickBooks:", str(e))
return None
def test_qbxml_request(qb, request_type):
"""Tests a minimal QBXML request."""
try:
# Generate a basic QBXML request based on the request_type
request = f"""
"""
print(f"Sending {request_type} request...")
response = qb.ProcessRequest(request)
print(f"Raw Response for {request_type}:", response) # Debugging output
return response
except Exception as e:
print(f"Error during {request_type}:", str(e))
return None
def parse_response(response, tag_name):
"""Parses the QBXML response and extracts elements by tag name."""
try:
root = ET.fromstring(response)
elements = root.findall(f".//{tag_name}")
print(f"Extracted {len(elements)} elements with tag '{tag_name}'")
for element in elements:
print(ET.tostring(element, encoding='unicode'))
except Exception as e:
print(f"Error parsing response for {tag_name}:", str(e))
def main():
"""Main function to test QBXML requests."""
qb = connect_to_quickbooks()
if not qb:
return
try:
# Test Company Query
company_response = test_qbxml_request(qb, "CompanyQueryRq")
if company_response:
parse_response(company_response, "CompanyName")
# Test Customer Query
customer_response = test_qbxml_request(qb, "CustomerQueryRq")
if customer_response:
parse_response(customer_response, "CustomerRet")
# Test Invoice Query
invoice_response = test_qbxml_request(qb, "InvoiceQueryRq")
if invoice_response:
parse_response(invoice_response, "InvoiceRet")
finally:
# Close the session and connection gracefully
try:
qb.EndSession()
except Exception as e:
print("Error during EndSession:", str(e))
try:
qb.CloseConnection()
except Exception as e:
print("Error during CloseConnection:", str(e))
if __name__ == "__main__":
main()
C:\python>py invoiceexport.py
Sending CompanyQueryRq request...
Error during CompanyQueryRq: (-2147352562, 'Invalid number of parameters.', None, None)
Sending CustomerQueryRq request...
Error during CustomerQueryRq: (-2147352562, 'Invalid number of parameters.', None, None)
Sending InvoiceQueryRq request...
Error during InvoiceQueryRq: (-2147352562, 'Invalid number of parameters.', None, None)
Error during EndSession: (-2147352562, 'Invalid number of parameters.', None, None)
Я знаю, что программа обращается к системе Quickbooks, потому что мне пришлось включить программу при первом запуске. Я предоставил программе полный доступ к файлу Quickbooks, даже если Quickbooks не запущен.
Я продолжаю получать сообщение «Неверное количество параметров», но не могу понять, что делаю неправильно. .
Код ниже с генерируемыми сообщениями об ошибках. [code]import win32com.client import xml.etree.ElementTree as ET
def connect_to_quickbooks(): """Establishes a connection to QuickBooks Desktop.""" try: qb = win32com.client.Dispatch("QBXMLRP2.RequestProcessor") qb.OpenConnection("", "QBXML Test App") qb.BeginSession("", 2) # 2 = qbFileOpenDoNotCare return qb except Exception as e: print("Error connecting to QuickBooks:", str(e)) return None
def test_qbxml_request(qb, request_type): """Tests a minimal QBXML request.""" try: # Generate a basic QBXML request based on the request_type request = f"""
""" print(f"Sending {request_type} request...") response = qb.ProcessRequest(request) print(f"Raw Response for {request_type}:", response) # Debugging output return response except Exception as e: print(f"Error during {request_type}:", str(e)) return None
def parse_response(response, tag_name): """Parses the QBXML response and extracts elements by tag name.""" try: root = ET.fromstring(response) elements = root.findall(f".//{tag_name}") print(f"Extracted {len(elements)} elements with tag '{tag_name}'") for element in elements: print(ET.tostring(element, encoding='unicode')) except Exception as e: print(f"Error parsing response for {tag_name}:", str(e))
def main(): """Main function to test QBXML requests.""" qb = connect_to_quickbooks() if not qb: return
try: # Test Company Query company_response = test_qbxml_request(qb, "CompanyQueryRq") if company_response: parse_response(company_response, "CompanyName")
# Test Customer Query customer_response = test_qbxml_request(qb, "CustomerQueryRq") if customer_response: parse_response(customer_response, "CustomerRet")
# Test Invoice Query invoice_response = test_qbxml_request(qb, "InvoiceQueryRq") if invoice_response: parse_response(invoice_response, "InvoiceRet") finally: # Close the session and connection gracefully try: qb.EndSession() except Exception as e: print("Error during EndSession:", str(e)) try: qb.CloseConnection() except Exception as e: print("Error during CloseConnection:", str(e))
if __name__ == "__main__": main() [/code] [code]C:\python>py invoiceexport.py Sending CompanyQueryRq request... Error during CompanyQueryRq: (-2147352562, 'Invalid number of parameters.', None, None) Sending CustomerQueryRq request... Error during CustomerQueryRq: (-2147352562, 'Invalid number of parameters.', None, None) Sending InvoiceQueryRq request... Error during InvoiceQueryRq: (-2147352562, 'Invalid number of parameters.', None, None) Error during EndSession: (-2147352562, 'Invalid number of parameters.', None, None) [/code] Я знаю, что программа обращается к системе Quickbooks, потому что мне пришлось включить программу при первом запуске. Я предоставил программе полный доступ к файлу Quickbooks, даже если Quickbooks не запущен. Я продолжаю получать сообщение «Неверное количество параметров», но не могу понять, что делаю неправильно. .