import pandas as pd
import os
header = '\n\n\n\n\nVouchers\n\n\n\n'
footer = '\n\n\n'
def debit_note(inputfile):
if not inputfile.lower().endswith('.csv'):
print('Error: Expected a CSV file')
return None
outputfile = os.path.splitext(inputfile)[0] + '.xml'
try:
df = pd.read_csv(inputfile)
except FileNotFoundError:
print('Error: CSV file not found')
return None
except pd.errors.EmptyDataError:
print('Error: CSV file is empty')
return None
except pd.errors.ParserError:
print('Error: CSV file is malformed or cannot be parsed')
return None
att = df.columns
srop = ''
for j in range(len(df)):
rowop = ''
v_type = ''
cost_centre = ''
cost_category = ''
invoice_num = ''
gstin = ''
date = ''
for i in range(len(att)):
row_value = str(df[att[i]][j]).replace('&', '&').replace('<', '<').replace('>', '>').replace("'", ''').replace('"', '"')
if row_value == 'emp' or att[i].startswith('Mailing'):
continue
if att[i].startswith('VOUCHERTYPENAME'):
v_type = row_value
rowop += f'<{att[i]}>{row_value}{att[i]}>\n'
continue
if att[i].startswith('CostCentre'):
cost_centre = row_value
continue
if att[i].startswith('Invoice'):
invoice_num = row_value
rowop += f'{row_value}\n'
continue
if att[i].startswith('CostCategory'):
cost_category = row_value
continue
if att[i].startswith('State_Name'):
if row_value != 'emp':
rowop += f'{row_value}\n{row_value}\n{row_value}\n'
continue
if att[i].startswith('POS'):
rowop += f'{row_value}\n{row_value}\n'
continue
if att[i].startswith('Registration_Type'):
continue
if att[i].startswith('Company_GSTIN'):
if row_value != 'emp':
rowop += f'{row_value}\n{row_value}\n'
gstin = row_value
continue
if att[i].startswith('DATE'):
date = row_value
rowop += f'<{att[i]}>{row_value}{att[i]}>\n{date}\n'
continue
if att[i].startswith('DebitLedger'):
if row_value != 'emp':
rowop += f'{row_value}\n{row_value}\n{row_value}\n\n{row_value}\n'
continue
if att[i].startswith('AmountDebit'):
if row_value != 'emp':
rowop += f'Yes\nYes\n{row_value}\n\n{invoice_num}\nAgst Ref\n{row_value}\n\n\n '
continue
if att[i].startswith('CreditLedger'):
if row_value != 'emp':
rowop += f'\n{row_value}\n'
continue
if att[i].startswith('AmountCredit'):
if row_value != 'emp':
if i == len(att) - 1:
rowop += f'No\nNo\n{row_value}\n\n{cost_category}\nYes\n\n{cost_centre}\n{row_value}\n\n\n\n\n\n'
else:
rowop += f'No\nNo\n{row_value}\n\n{cost_category}\nYes\n\n{cost_centre}\n{row_value}\n\n\n\n '
continue
else:
rowop += f'<{att[i]}>{row_value}{att[i]}>\n'
srop += f'\n\n' + rowop
entireop = header + srop + footer
try:
with open(outputfile, 'w') as f:
f.write(entireop)
print(f"XML file created successfully: {outputfile}")
except Exception as e:
print(f"Error writing XML file: {e}")
return None
return outputfile
# Example usage
debit_note('dn.csv')