简体   繁体   English

从CSV文件读取数据并将其插入Salesforce

[英]Reading data from CSV file and insert into Salesforce

I am trying to read data from a csv file and insert/upsert (depending on existent of UniqueId) into Salesforce using Python. 我正在尝试从csv文件读取数据,然后使用Python将数据插入/向上插入(取决于UniqueId的存在)。

I know I have to use iterator to read data from a cvs file, put them into List, but I am not sure how to fetch the data from that List and put (insert or upsert) data in Salesforce. 我知道我必须使用迭代器从cvs文件中读取数据,然后将其放入List中,但是我不确定如何从该List中获取数据并将数据插入(插入或向上插入)Salesforce中。

Each csv file contains two fields (UniqueId, Selection). 每个csv文件包含两个字段(UniqueId,选择)。

Do I use enumerate ? 我使用enumerate吗?

Here is what I have so far (where action taking place): 这是我到目前为止(正在执行操作的地方):

How do I fetch the data into Salesforce? 如何将数据提取到Salesforce中?

InFiles = glob.glob(inputFolderName + '/SurveySelection*.csv')

InFileslist = []       ##List to put file name
for InFile in InFiles:
    thenStamp = os.path.getmtime(InFile)

    if (thenStamp >= unix_time(dt1)) and (thenStamp >= unix_time(dt2)):
       InFileslist.append(InFile)  ## Expression to append files in certain time range

for filename in InFileslist:
    file = open(filename, 'r')
    lines = file.readlines()

Not too sure what your requirements are, but if you are not integrating two systems why not just import the data directly using tools provided by salesforce like the data import wizard or Salesforce DataLoader? 不太清楚您的要求是什么,但是如果不集成两个系统,为什么不直接使用由Salesforce提供的工具(如数据导入向导或Salesforce DataLoader)直接导入数据呢? If you are integrating systems then you should look into using the Salesforce REST API, or by using the Salesforce python sdk 如果要集成系统,则应考虑使用Salesforce REST API或使用Salesforce python sdk

pip install salesforce-python-sdk pip安装salesforce-python-sdk

You are currently in the same position I was about 8 months ago. 您目前处于大约8个月前的位置。 I have successfully integrated a MySQL Database into Salesforce. 我已成功将MySQL数据库集成到Salesforce中。 Basically a customer will register a product on our website, then I have python pull the data from the database, format it all in a xlsx file and then send that data into salesforce using simple-salesforce package which works great. 基本上,客户会在我们的网站上注册产品,然后我用python从数据库中提取数据,将其全部格式化为xlsx文件,然后使用效果很好的simple-salesforce软件包将该数据发送到salesforce。 Below is a code snippet which should help you get started. 以下是一个代码片段,可以帮助您入门。 Let me know if you have any questions. 如果您有任何疑问,请告诉我。

import os
import sys
import xlrd
import xlwt
import time
import base64
import smtplib
import MySQLdb
import logging
import datetime
import collections
from xlrd.sheet import ctype_text
from collections import OrderedDict
from simple_salesforce import SFType
from simple_salesforce import Salesforce
from xlsxwriter.workbook import Workbook
from MySQLdb import OperationalError
from mysql.connector import MySQLConnection, Error

logger = logging.getLogger('view_rows')
hdlr = logging.FileHandler('C:\Users\Chris\Documents\Email Logs\myapp.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.WARNING)
# MySQL Database Credentials
ur = 'user_name' # your username
pd = 'my_password' # your password
ht = 'localhost' # your host
pt = 3306
db = 'my_database' # database where your table is stored
con = MySQLdb.connect(user=ur, passwd=pd, host=ht, port=pt, db=db)
cursor = con.cursor()
con.autocommit(True)
# Salesforce Credentials
sf = Salesforce(username='my_Salesforce_Email@mail.com', password='my_SF_password', security_token='my_Generated_token_from_Salesforce', client_id='This does not really matter')
orderedDict = collections.OrderedDict()
# Gets the new customers that have created an account on the Warranty Portal
def GetNewContact():
        # Creates a xlsx file
    workbook = Workbook('outfile.xlsx')
    sheet = workbook.add_worksheet("Warranty Info")
    query = "SELECT RC.cus_id, RC.cus_username, RC.cus_subsc FROM my_database.rma_customer RC INNER JOIN my_database.rma_customer_address CA ON RC.cus_id=CA.cus_id WHERE CA.cus_address_type=0 AND CA.cus_updated=1"
    query0 = "SELECT RCD.cus_firstname, RCD.cus_lastname, RCD.cus_cell_phone FROM my_database.rma_customer_details RCD INNER JOIN my_database.rma_customer_address CA ON RCD.cus_id=CA.cus_id WHERE CA.cus_address_type=0 AND CA.cus_updated=1"
    query1 = "SELECT CA.cus_address_1, CA.cus_address_2, CA.cus_city, CA.cus_postcode FROM my_database.rma_customer_address CA LEFT JOIN my_database.rma_customer RC ON CA.cus_id=RC.cus_id WHERE CA.cus_address_type=0 AND CA.cus_updated=1"
    cursor.execute(query)
    headers = ['ID', 'Email', 'Newsletter', 'FirstName', 'LastName', 'Phone', 'Street', 'APT', 'City', 'Postal']
    for i, header in enumerate(headers):
        sheet.write(0, i, header)
    for r, row in enumerate(cursor.fetchall()):
        r = r + 1
        for c, col in enumerate(row):
            sheet.write(r, c, col)              
    cursor.execute(query0)  
    for r, row in enumerate(cursor.fetchall()):
        r = r + 1
        for c, col in enumerate(row):
            sheet.write(r, c+3, col)        
    cursor.execute(query1)  
    for r, row in enumerate(cursor.fetchall()):
        r = r + 1
        for c, col in enumerate(row):
            sheet.write(r, c+6, col)
     #Updates the database after it has grabbed the needed info to create a contact in salesforce so that it does not get that same data again
    workbook.close()
def CreateContact():
    # Knows what file to look into for the information to create a contact
    path = 'outfile.xlsx'
    workbook = xlrd.open_workbook(path, on_demand = True)
    sheet = workbook.sheet_by_index(0)
    for rowx in xrange(1, sheet.nrows):
        try:
            Id = sheet.row_values(rowx, start_colx=0, end_colx=None)[0]
            Email1 = sheet.row_values(rowx, start_colx=1, end_colx=None)[0]
            Newsletter = sheet.row_values(rowx, start_colx=2, end_colx=None)[0]
            First = sheet.row_values(rowx, start_colx=3, end_colx=None)[0]
            Last = sheet.row_values(rowx, start_colx=4, end_colx=None)[0]
            Phone = sheet.row_values(rowx, start_colx=5, end_colx=None)[0]
            Street = sheet.row_values(rowx, start_colx=6, end_colx=None)[0]
            Apt = sheet.row_values(rowx, start_colx=7, end_colx=None)[0]
            City = sheet.row_values(rowx, start_colx=8, end_colx=None)[0]
            Postal = sheet.row_values(rowx, start_colx=9, end_colx=None)[0]
            d = sf.query("SELECT Id FROM Contact WHERE Phone ='%s' OR Email='%s'" % (Phone, Email1))
            # d = returns more than just a case number so data = will specifically only get the case number 
            data = [e["Id"] for e in d["records"]]
            sf.Contact.update(data[0],{'OwnerId' : "005U0000005jwPH", 'Phone' : Phone, 'Email' : Email1, 'Newsletter__c' : Newsletter, 'MailingStreet' : Street+" "+Apt, 'MailingCity' : City, 'MailingPostalCode' : Postal, 'AccountId' : "001U000001ZEB89"})
            cursor.execute("UPDATE rma_customer AS RC INNER JOIN rma_customer_address CA ON RC.cus_id = CA.cus_id SET RC.SF_created=1 WHERE RC.cus_id='%s'" % Id)   
            cursor.execute("UPDATE rma_customer_address AS CA INNER JOIN rma_customer RC ON CA.cus_id = RC.cus_id  SET CA.SF_created=1 WHERE CA.cus_id='%s'" % Id)
            cursor.execute("UPDATE rma_customer_address AS CA INNER JOIN rma_customer RC ON CA.cus_id = RC.cus_id SET CA.cus_updated=0 WHERE CA.cus_id='%s'" % Id)
            cursor.execute("UPDATE rma_customer_details AS RCD INNER JOIN rma_customer RC ON RCD.cus_id = RC.cus_id SET RCD.SF_created=1 WHERE RCD.cus_id='%s'" % Id)
        # If Contact exists, skips and goes to next customer in excel sheet.
        except Exception, e:
            #print "Exception %s"%str(e)
            Id = sheet.row_values(rowx, start_colx=0, end_colx=None)[0]
            Email1 = sheet.row_values(rowx, start_colx=1, end_colx=None)[0]
            Newsletter = sheet.row_values(rowx, start_colx=2, end_colx=None)[0]
            First = sheet.row_values(rowx, start_colx=3, end_colx=None)[0]
            Last = sheet.row_values(rowx, start_colx=4, end_colx=None)[0]
            Phone = sheet.row_values(rowx, start_colx=5, end_colx=None)[0]
            Street = sheet.row_values(rowx, start_colx=6, end_colx=None)[0]
            Apt = sheet.row_values(rowx, start_colx=7, end_colx=None)[0]
            City = sheet.row_values(rowx, start_colx=8, end_colx=None)[0]
            Postal = sheet.row_values(rowx, start_colx=9, end_colx=None)[0]
            logger.error("Unable to Create Contact: "+Email1+" "+Phone)
            logger.error(e)
            sf.Contact.create({'FirstName' : First, 'LastName' : Last, 'Newsletter__c' : Newsletter, 'Email' : Email1, 'Phone' : Phone, 'MailingStreet' : Street+" "+Apt, 'MailingCity' : City, 'MailingPostalCode' : Postal, 'AccountId' : "001U000001ZEB89"})
            #print "Contact Not Found. Created New Contact!"
            cursor.execute("UPDATE rma_customer AS RC INNER JOIN rma_customer_address CA ON RC.cus_id = CA.cus_id SET RC.SF_created=1 WHERE RC.cus_id='%s'" % Id)   
            cursor.execute("UPDATE rma_customer_address AS CA INNER JOIN rma_customer RC ON CA.cus_id = RC.cus_id  SET CA.SF_created=1 WHERE CA.cus_id='%s'" % Id)
            cursor.execute("UPDATE rma_customer_address AS CA INNER JOIN rma_customer RC ON CA.cus_id = RC.cus_id SET CA.cus_updated=0 WHERE CA.cus_id='%s'" % Id)
            cursor.execute("UPDATE rma_customer_details AS RCD INNER JOIN rma_customer RC ON RCD.cus_id = RC.cus_id SET RCD.SF_created=1 WHERE RCD.cus_id='%s'" % Id)
            #time.sleep(10)
        # Sleep for 30 seconds to allow Salesforce to catch up before creating the cases to ensure they are correctly associated
    workbook.release_resources()
    time.sleep(5)

GetNewContact()
CreateContact()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM