[SalesForce] How to upload an Excel file into ContentVersion Object

I need to upload an Excel file on an opportunity. I want to user ContentVersion standard object to store these excel files.

Can anyone please explain or share a code snippet to show how can we
upload an excel to an ContentVersion object and how to associate the
uploaded record with an opportunity?

can you please also explain difference between ContentVersion and
ContentDocument objects?

Thanks in advance

Best Answer

Have a look at the Content Objects Data Model for the relationship between ContentVersion and ContentDocument.

Content Objects Schema

One ContentDocument can have one or more ContentVersion records. The ContentVersion contains the actual data.

Use the ContentVersion to create the new record. The Excel file data should be stored in the VersionData field. You will also want to set the Title and PathOnClient (including the file extension) fields.

The ContentDocumentLink can be used to create the link to a record that supports chatter feed tracking (including custom objects).