Java Code: Export Salesforce Attachements to Dropbox

I wrote a class the exports Salesforce Attachements to be exported to your local Machine. I put the exported attachement files in a dropbox folder which is automatically the shared with others in the organization.

Note: make sure the export directory is shared on Dropbox.

package com.thys.michels.sfdc.doc;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;

import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.sobject.Attachment;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

public class SFDCDoc {

	/**
	 * @param args
	 * @throws NumberFormatException 
	 * @throws IOException 
	 * @throws URISyntaxException 
	 * @throws DOMException 
	 */
	public static void main(String[] args) throws NumberFormatException, IOException, URISyntaxException {
		// TODO Auto-generated method stub
		

	   //Create a new connectionconfig to your Salesforce Org
	    ConnectorConfig sfconfig = new ConnectorConfig();
	    //Use your salesforce username = email
	    sfconfig.setUsername("yourusername");
	    //Use your saleforce password with your security token look like: passwordjeIzBAQKkR6FBW8bw5HbVkkkk
	    sfconfig.setPassword("passwordwithsecuritytoken");
	 
	    EnterpriseConnection partnercon = null;
	    
	    try {
	    	 
	        // create a salesforce connection object with the credentials supplied in your connectionconfig
	        partnercon = Connector.newConnection(sfconfig);
	        QueryResult describeGlobalResult = partnercon.query("select Id, Name, Body from Attachment where ContentType='application/pdf'");
	        System.out.println(describeGlobalResult.getRecords().length);
	        boolean done = false;
	     
	        while(!done)
	        {
	        	for (int k = 0; k < describeGlobalResult.getRecords().length; k++)
	        	{
	        		
	        	    Attachment a = (Attachment)describeGlobalResult.getRecords()[k];
	        	    File path = new File("//Users//tmichels//Dropbox//SFDCAttachments");
	        	    String mySubFolder = a.getId();
	        	    File newDir = new File(path + File.separator + mySubFolder);
	        	    System.out.println(newDir);
	        	    boolean success = newDir.mkdirs();
	        	    FileOutputStream fos = new FileOutputStream(newDir + File.separator+ a.getName());
	        	    fos.write(a.getBody());
	        	    fos.close();
	        	}
	        	if (describeGlobalResult.isDone()) {
	                done = true;
	             } else {
	            	 describeGlobalResult = partnercon.queryMore(describeGlobalResult.getQueryLocator());
	             }
	        }
	        
	        
	    } catch (ConnectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
	    }
	}
}

Java Code: Salesforce Export into Excel

Export Salesforce records into Excel. In my example I read records from Excel and also from Salesforce. Reuse my code by providing your own username and password to your Salesforce org to create more advanced SFDC to Excel integrations. You will need to download or add jxl to your maven project:

http://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl

package com.thys.michels; 
import java.io.File;
import java.io.IOException;
import java.util.Locale;

import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.DescribeSObjectResult;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.soap.partner.QueryResult;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import jxl.CellView;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class ForcedotcomExcelToolkit {
    private WritableCellFormat times;
    private String inputFile;
    private WritableCellFormat timesBoldUnderline;

    public void setInputFile(String inputFile) {
        this.inputFile = inputFile;
    }
    public void setOutputFile(String inputFile) {
        this.inputFile = inputFile;
    }

    public String[] read() throws IOException  {
        File inputWorkbook = new File(inputFile);
        Workbook w;
        try {
            w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
            Sheet sheet = w.getSheet(0);
// Loop over first 10 column and lines

            String arremail[] = new String[246];

            for (int j = 0; j &lt; sheet.getColumns(); j++) 
            {
                for (int i = 0; i &lt; sheet.getRows(); i++) 
                {
                    Cell cell = sheet.getCell(j, i);
                    CellType type = cell.getType();
                    if (cell.getType() == CellType.LABEL) {
                        arremail[i] = cell.getContents();
                    }
                }
            }
            return arremail;
        } 
        catch (BiffException e) 
        {
            e.printStackTrace();
            return null;
        }
    }

    public void write(String[][] arremail) throws IOException, WriteException {
        File file = new File(inputFile);
        WorkbookSettings wbSettings = new WorkbookSettings();
        wbSettings.setLocale(new Locale("en", "EN"));
        WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
        workbook.createSheet("Report", 0);
        WritableSheet excelSheet = workbook.getSheet(0);
        createLabel(excelSheet);
        System.out.println(arremail.length);
        for (int i = 1; i &lt; arremail.length; i++) 
        {
// First column
            if (arremail[i-1][0]!=null)
                addLabel(excelSheet, 0, i, arremail[i-1][0].toString());
// Second column
            if (arremail[i-1][1]!=null)
                addLabel(excelSheet, 1, i, arremail[i-1][1].toString());
        }
//createContent(excelSheet, arremail);
        System.out.println("Done 8");
        workbook.write();
        workbook.close();
    }
//private void createContent(WritableSheet sheet, String[][] arremail) throws WriteException,RowsExceededException {
// Write a few number

//}

    private void createLabel(WritableSheet sheet)
            throws WriteException {
// Lets create a times font
        WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
// Define the cell format
        times = new WritableCellFormat(times10pt);
// Lets automatically wrap the cells
        times.setWrap(true);

// Create create a bold font with unterlines
        WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,
                UnderlineStyle.SINGLE);
        timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
// Lets automatically wrap the cells
        timesBoldUnderline.setWrap(true);

        CellView cv = new CellView();
        cv.setFormat(times);
        cv.setFormat(timesBoldUnderline);
        cv.setAutosize(true);

// Write a few headers
        addCaption(sheet, 0, 0, "Email");
        addCaption(sheet, 1, 0, "Phone");

    }
    private void addCaption(WritableSheet sheet, int column, int row, String s)
            throws RowsExceededException, WriteException {
        Label label;
        label = new Label(column, row, s, timesBoldUnderline);
        sheet.addCell(label);
    }

    private void addLabel(WritableSheet sheet, int column, int row, String s)
            throws WriteException, RowsExceededException {
        Label label;
        label = new Label(column, row, s, times);
        sheet.addCell(label);
    }

    public String[][] SFDCEmailResult(String [] stremail)
    {
//Create a new connectionconfig to your Salesforce Org
        ConnectorConfig sfconfig = new ConnectorConfig();
//Use your salesforce username = email
        sfconfig.setUsername("yourusername");
//Use your saleforce password with your security token look like: passwordjeIzBAQKkR6FBW8bw5HbVkkkk
        sfconfig.setPassword("yourpassword");
        sfconfig.setConnectionTimeout(99999);
        PartnerConnection partnercon;
        try
        {
            partnercon = Connector.newConnection(sfconfig);
            DescribeSObjectResult describeGlobalResult = partnercon.describeSObject("Contact");
//DescribeGlobalSObjectResult[] sobjectResults = describeGlobalResult.getSobjects();
            String [][] emailresult = new String[246][246];
            for (int k = 0; k &lt; stremail.length; k++)
            {
                String QueryStr = "SELECT Email, Phone FROM Contact where Email='" + stremail[k]+"'";
                QueryResult queryResults = partnercon.query(QueryStr);
                if (queryResults.getSize() &gt; 0)
                {
                    for (SObject s: queryResults.getRecords())
                    {
                        emailresult[k][0] = s.getField("Email").toString();
                        if (s.getField("Phone") != null)
                            emailresult[k][1] = s.getField("Phone").toString();
                        else
                            emailresult[k][1]="";
                    }
                }
            }
            return emailresult;
        }
        catch(ConnectionException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws IOException, WriteException
    {
        ForcedotcomExcelToolkit outemailexcelinput = new ForcedotcomExcelToolkit();
        outemailexcelinput.setInputFile("/Users/tmichels/Documents/SFDCEmail.xls");
        System.out.println("Complete Reading Emails from Excel");
        ForcedotcomExcelToolkit outemailexceloutput = new ForcedotcomExcelToolkit();
        outemailexceloutput.setOutputFile("/Users/tmichels/Documents/SFDCEmailResults.xls");
        outemailexceloutput.write(outemailexceloutput.SFDCEmailResult(outemailexcelinput.read()));
        System.out.println("Complete Writing Emails");
    }