Saturday, April 6, 2013

Sending office document content from Office App to server side

So here goes another post for App for Office Api. This post will focus on providing you with some basic knowledge on sending the whole document from your app to your server side code.
The sample I tried on is built on MVC4, but it necessarily doesn't mean that this thing is possible on or MVC only. Any server side language that can handle ajax calls and can convert base 64 string to byte array can do :)

Another thing to note down here is that this sample will use one of my javascript library that I named it "OffQuery". This library is just a wrapper on top of Office.js javascript api aiming at hiding most of the complexities for simple functionalities. It also supports jquery's promise giving you a more flexible and jquery way to handle Office.js asynchronous calls. For more on it I'd suggest visiting jquery site and get your hands dirty with couple of samples yourself.  "OffQuery" is still in it's infancy and hope to post some more examples , if I'm able to continue on it. But today let's focus on learning how can we send the whole office document from your app to server side and write on your disk.

I won't be going in detail on setting up your project for this tutorial, which obviously varies depending on the server side language you are familiar with. However in this sample I'll show you a way to get your document content using OffQuery and then a simple Mvc controller action that handles the ajax calls and write the content to disk. If you are an MVC developer and want to convert your MVC project to App for office project then you can visit my previous posts "Convert existing web project to office app using Visual Studio 2012" and "Convert App For Office Project to MVC Project Type"

For this tutorial make sure you include MicrosoftAjax.js, Office.js, Jquery OffQuery.js. For jquery you can download the latest file from jquery site and for OffQuery you can visit
After that write javascript to handle Office.initialize function. Please make sure you do this before calling any of the Office or OffQuery api's

Next write your javascript to get the document content in byte array.

function saveContent() {

    $.when(OffQuery.getContent({ sliceSize: 50000 }, function (j, data, result, file, opt) {
        var temp = data;

    })).then(function (finalByteArray, file, opt) {
        //this function is called at the end.
        //FullData contains byte array.
        //file is the file object of Office.js
        //opt is the option supplied at the very beginning when calling OffQuery.getContent() function.
        var fileContent = OSF.OUtil.encodeBase64(finalByteArray); //encode the byte array into base64 string.

    }).progress(function(j, chunkOfData, result, file, opt){
        //handle the progress here.

This function basically leverages the jquery's new inbuilt asynchronous api $.when. The anonymous function provided in then function will be called after the asynchronous call to getContent function is complete. If you have been using office.js then you probably have noted that it's very simple to get the whole content at once using OffQuery rather than using the Office.context.document.getFileAsync() function, providing your own implementation to handle the recursive calls and all. The OSF.OUtil.encodeBase64() function converts your byte array to Base64 string ready for sending it to your server.

function sendFileMethod(fileContent) {

        url: saveContentUrl,
        data: { contentByte: fileContent },
        type: 'POST'

    }).then(function (a, b, c) {
        var tempa = a;
        var tempb = b;


sendFileMethod doesn't do much than sending the content to server using jquery's ajax call.

public JsonResult SaveContent(string contentByte)
            var byteArr2 =Convert.FromBase64String(contentByte);//convert the base64 string to byte array
            using (var fileStream = System.IO.File.OpenWrite(@"c:\tempfolder\tempfile.docx")) //open a file
                fileStream.Write(byteArr2, 0, byteArr2.Length); //write the byte array as content in the file

            return Json(new { success=true});

The server side code is self explanatory. It simply converts the base64 string to byte array, opens a .docx file on disk and then writes the byte array. The code provided is in MVC.

Download the sample code from here.

1 comment:

  1. I am very new at this stage but i want to make myself as a Visual Studio Expert. I trying to make a automated software via Visual Studio 2012. I want, it will auto "sign in" in my 5 twitter accounts and follow a user one by one and after that it will auto log out. For Example, I will input in the box usernames and passwords like this ------ username1:password


    username3:password and continue

    And into other box i will input the username which need followers.

    I need after i click my button, it will start auto sign in into my twitter accounts and follow my preferred user and then it sign out and again it start and complete all 5 accounts.

    A radio button is also available there.

    Please help me as soon as possible, i have no any dishonest reason, i just want to learn it. I know many expert and helpful are available here.

    Thanks and waiting for your reply.

    My created code: Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If RadioButton1.Checked = True Then
    ?????????????? (I don't know what i do here)
    End If