Create CSV file in SharePoint by passing content in REST API Body

Rwithu kovakkallil 0 Reputation points
2023-06-23T14:25:36.81+00:00

Hi All,

I am trying to create a CSV file in sharepoint using REST API by passing content in body(Text/csv). I am able to create file but formatting is not as expected. Unable to add Newline in CSV file created.

Can someone help me out here.

Thanks in advance

Microsoft 365 and Office | Development | Office JavaScript API
Microsoft 365 and Office | SharePoint | For business | Windows
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-06-26T03:59:34.07+00:00

    Hi @Rwithu kovakkallil,

    Please try to use \n to split the content to be passed.

    Like this:

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://MyServer/sites/SiteCollection/style library/js/ScriptFile.js"></script>
    <script>
    function createCSVFile() {
      var webServerRelativeUrl = _spPageContextInfo.webServerRelativeUrl;
      var documentLibraryInternalName = "Document%20Library";
    
      var fileContent = "Header1,Header2,Header3\nValue1,Value2,Value3\nValue4,Value5,Value6";
    
      var serverRelativeUrlOfFile = _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('" + webServerRelativeUrl + "/" + documentLibraryInternalName + "')/Files/add(url='Test.csv',overwrite=true)";
    
      $.ajax({
        url: serverRelativeUrlOfFile,
        type: "POST",
        headers: {
          "Accept": "application/json;odata=verbose",
          "Content-Type": "text/csv",
          "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        data: fileContent,
        success: function(data, status, xhr) {
          console.log("CSV file created successfully");
        },
        error: function(xhr, status, error) {
          console.log("Failed to create CSV file");
        }
      });
    }
    </script>
    <button onclick="createCSVFile();" type="button">Click me</button>
    
    
    

    Here is result:

    User's image


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards

    Cheng Feng

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.