Salesforce Export Database Records to CSV for Batch Upload

Exporting of Database records to csv can be done using:

1. OpenCSV CSVWriter
2. FileWriter

1. OpenCSV CSVWriter


	@Inject
    private Environment environment;

	@Inject @Named("proddataSource") DataSource dataSource;

	private FileWriter writer;
	
	@Override
	public ResultSet getDWRecords(String queryName) {
		try {
			java.sql.PreparedStatement ps = dataSource.getConnection().prepareStatement(environment.getProperty(queryName));
			ps.setMaxRows(10000);
			ResultSet rs = ps.executeQuery();
			return rs;
		} catch (SQLException e) {
			logger.error("CreateCSVDWDumpFileImpl.getDWRecords(): " + e.getMessage());
		}
      return null;
	}

	@Override
	public void createCSVDumpFromQuery(ResultSet resultSet, String[] salesforceColumnNames, String fileName) {
		if (resultSet!=null){
			try {
				CSVWriter writer = new CSVWriter(new FileWriter(fileName), ',', CSVWriter.NO_QUOTE_CHARACTER);
				writer.writeNext(salesforceColumnNames);
				writer.writeAll(resultSet, false);
	            writer.close();
			} catch (IOException e) {
				logger.error("CreateCSVDWDumpFileImpl.createCSVDumpFromQuery(): " + e.getMessage());
			} catch (SQLException e) {
				logger.error("CreateCSVDWDumpFileImpl.createCSVDumpFromQuery(): " + e.getMessage());
			}
		}
	}

2. FileWriter

private FileWriter writer;
public void writeToCSVFileAccount(Collection<SObject> sObjects, String[] salesforceColumnNames, String fileName) {
	try {
		writer = new FileWriter(fileName);
		for (int firstCol = 0; firstCol < salesforceColumnNames.length; firstCol++){
			 writer.append(salesforceColumnNames[firstCol]);
			 if (firstCol < salesforceColumnNames.length-1)
				 writer.append(',');
		}
		writer.append('\n');
		
		for (SObject sAccount : sObjects){
			for (int k = 0; k < salesforceColumnNames.length; k++){
				writer.append(sAccount.getField(salesforceColumnNames[k])!=null ? salesforceColumnNames[k].contains("Date") || salesforceColumnNames[k].contains("date") ?  String.format("%1$tF", sAccount.getField(salesforceColumnNames[k])) : sAccount.getField(salesforceColumnNames[k]).toString() : "");
				if (k < salesforceColumnNames.length-1)
					writer.append(',');
			}
			writer.append('\n');
		}
		
		writer.flush();
		writer.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		}
	}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: