1

Is their any specific headers need to set while creating .xlsx file in SharePoint?

I have used the below Rest API code in postman to create the one but getting the attached error while opening the created one in SharePoint.

url: http://siteurl/_api/web/GetFolderByServerRelativeUrl('/FolderName')/Files/add(url='a.xlsx',overwrite=true)
method: POST
body: "Contents of file in raw plain text"
Headers: 
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    content-length:length of post body

enter image description here

To me it looks like the issue is with the format/content type of the file which i tried to set via header Content-Type : "application/vnd.ms-excel" but still no luck. Please note i am trying this from Postman

Below is the header section screenshot from Postman

enter image description here

1
  • 1
    you cannot just make an Excel document out of raw plain text. Try this: take your plain text and put it into a text file, then change its extension to xlsx and try to open it. Does it work? That's what you're basically doing here. – Derek Gusoff Dec 27 '19 at 14:21
0

Try using below code to create a file in SharePoint library:

var restUrl = "http://siteurl/_api/web/GetFolderByServerRelativeUrl('/sites/siteName/DocumentLibrary/FolderName')/Files/add(url='a.xlsx', overwrite=true)";

jQuery.ajax({
    url: restUrl,
    type: "POST",
    headers: {        
        "accept": "application/json;odata=verbose", 
        "X-RequestDigest": $("#__REQUESTDIGEST").val(); 
    },
    success: function(data){
        console.log(data);
    },
    error: function(data){
        console.log(data);
    }
});

Note: You need to pass the complete server relative URL of folder inside document library to create a file in specific folder.

2
  • It is unable to open the file after uploading by this ajax call. – Raf Dec 26 '19 at 5:34
  • the file is getting created successfully in the documents folder as expected, the issue (error as attached) is coming in opening the file. – Arpit Bhardwaj Dec 26 '19 at 6:08
0

Ajax call listed below works in case of file extension is xls. It doesn't work in case of xlsx. I think there should be special syntax to create valid .xlsx file.

Probably this question isn't about headers but about creating valid .xlsx file.

var fileContent = 'aaa';

jQuery.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('/testLib')/Files/add(url='a.xls',overwrite=true)",
        method: "POST",
        cache: true,
        data: fileContent,
        headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-length": fileContent.length
            },
        success: alert("Yeah"),
        error: function (err) {
            console.log(err.responseText);
        }
    });
3
  • i tried both xls and xlsx, the file is getting created successfully in the documents folder as expected, the issue (error as attached) comes while opening the file – Arpit Bhardwaj Dec 26 '19 at 6:24
  • @ArpitBhardwaj I tried call above. I can open xls file that was uploaded by this rest call. – Raf Dec 26 '19 at 6:33
  • i think you are right, the issue is about the valid xls content. Will check it in this direction. – Arpit Bhardwaj Dec 27 '19 at 8:08
0

In the POST man tool select the binary option where it will allow to attach or browse any file - there you attach any excel file by browsing your local directory - then perform the POST operation to SharePoint, this will upload the document to the SharePoint library - then go to the code section of the POST man tool where we can all equivalent code for this POST operation in almost all coding language like C#, JSON, REST API etc. Then look at the C# coding structure how it got generated automatically and we can use this format of code wherever we want.

Binary option selection example:

Binary option selection example

How to get the code snippet from POST man tool:

How to get the code snippet from POST man tool

Example:

Using the below C# REST API code we can add file to SharePoint:

var fileName = Path.GetFileName(uploadFilePath);
var requestUrl = string.Format("{0}/_api/web/Lists/GetByTitle('{1}')/items({2})/AttachmentFiles/add(FileName='{3}')", webUrl, listTitle, itemId,fileName);
var request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Credentials = credentials;  //SharePointOnlineCredentials object 
request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");

request.Method = "POST";
request.Headers.Add("X-RequestDigest", requestDigest);

var fileContent = System.IO.File.ReadAllBytes(uploadFilePath);
request.ContentLength = fileContent.Length;
using (var requestStream = request.GetRequestStream())
{
    requestStream.Write(fileContent, 0, fileContent.Length);
}

var response = (HttpWebResponse)request.GetResponse();

Reference URL:

upload attachment to SharePoint List Item using REST API from Java client

https://social.msdn.microsoft.com/Forums/office/en-US/40b0cb04-1fbb-4639-96f3-a95fe3bdbd78/upload-files-using-rest-api-in-sharepoint-2013?forum=sharepointdevelopment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.