Export MDX Result As Excel

Excel Export In MDX

In this post we will see how we can export mdx query result. Here we are going to use MVC with the help of jQuery Ajax. We will run the MDX query and get the cell set and then we will convert this cell set to html table so that we can render this html table easily in client side. Once we render the html table we will do some manipulations with the data, to increase the readability. We use one jQuery Ajax Call, One Controller, One function to execute the query and get cell set, and another function to convert the cell set to html table. And at last the controller will return the html table to the ajax success. And then we will export the data in client side. Simple right? Then let us move on. I hope you will like this article.

You can always read the about Microsoft ADOMD, MDX Queries and Cell Set here: Microsoft ADOMD,MDX,CellSet

Background

Recently I got a requirement to export the MDX query result to Excel. When a user clicks on a button I needed to export the MDX query result of the cube given. Here in this post I am sharing you the process I have done.

Using the code

First of all you need to create a button in your page to fire the click event.

[html]
<input type="submit" class="exprotbutton" value="Export to Excel" id=’excelExport’ />
[/html]

Now you need to load the jQuery reference to the page.

[js]
<script src="Scripts/jquery-1.11.1.min.js"></script>
[/js]

The next thing is to fire the click event.

[js]
$(‘#excelExport’).bind(‘click’, function (e) {
try {
} catch (e) {
console.log(‘Excel Export Grid: ‘ + e.message);
}
});
[/js]

Now we will create an ajax call to our controller.

[js]
$.ajax({
url: ‘../Exporting/Export/’,
type: ‘GET’,
dataType: ‘json’,
contentType: ‘application/json; charset=utf-8’,
success: function (data) {
},
error: function (xhrequest, ErrorText, thrownError) {
console.log(‘Excel Export Grid: ‘ + thrownError);
}

});
[/js]

Here Exporting is the controller name and Export is the action name

Have you noticed that we have not created the action yet. No worries we will create it now.

[csharp]
public JsonResult Export()
{
StringBuilder sbConnectionString = new StringBuilder();
sbConnectionString.Append("Provider=MSOLAP;data source=");
sbConnectionString.Append(serverName + ";initial catalog=" + databaseName + ";Integrated Security=SSPI;Persist Security Info=False;");

string readString = myModel.ExCellSet(query, sbConnectionString.ToString());
return Json(readString, JsonRequestBehavior.AllowGet);
}
[/csharp]

Here serverName, databaseName and query are the global variable I set. You can pass your own here.

Now we are passing the query and connection string to our model myModel and fire call the function ExCellSet. This ExCellSet function will execute the query and return the cell set. So shall we create that model function?

[csharp]
public string ExCellSet(string query, string adoMDConnection)
{
string readerString = string.Empty;
CellSet cst = null;
AdomdConnection conn = new AdomdConnection(adoMDConnection);
try
{
try
{
conn.Open();
}
catch (Exception){
}

using (AdomdCommand cmd = new AdomdCommand(query, conn))
{
cmd.CommandTimeout = connectionTimeout;
cst = cmd.ExecuteCellSet();
}
if (cst.Axes != null)
{
readerString = BuildHTML(cst);
return readerString;
}
else
return null;
}

catch (Exception)
{
cst = null;
throw;
}
finally
{
conn.Close(false);
cst = null;
}
}
[/csharp]

So our cell set is ready now we need to convert this cell set to the HTML table right? For that I strongly recommend you to read here: Convert CellSet to HTML Table

Anyway I am pasting the code here for your reference.

[csharp]

try
{
System.Text.StringBuilder result = new System.Text.StringBuilder();
//check if any axes were returned else throw error.
int axes_count = cst.Axes.Count;
if (axes_count == 0)
throw new Exception(“No data returned for the selection”);
//if axes count is not 2
if (axes_count != 2)
throw new Exception(“The sample code support only queries with two axes”);
//if no position on either row or column throw error
if (!(cst.Axes[0].Positions.Count > 0) && !(cst.Axes[1].Positions.Count > 0))
throw new Exception(“No data returned for the selection”);
int cur_row, cur_col, col_count, row_count, col_dim_count, row_dim_count;
cur_row = cur_col = col_count = row_count = col_dim_count = row_dim_count = 0;
//Number of dimensions on the column
col_dim_count = cst.Axes[0].Positions[0].Members.Count;
//Number of dimensions on the row
if (cst.Axes[1].Positions[0].Members.Count > 0)
row_dim_count = cst.Axes[1].Positions[0].Members.Count;
//Total rows and columns
row_count = cst.Axes[1].Positions.Count +
col_dim_count; //number of rows + rows for column headers
col_count = cst.Axes[0].Positions.Count +
row_dim_count; //number of columns + columns for row headers
//gridPanel.ClientIDMode = System.Web.UI.ClientIDMode.AutoID;
//////lets clear any controls under the grid panel
//gridPanel.Controls.Clear();
////Add new server side table control to gridPanel
Table tblgrid = new Table();
tblgrid.Attributes.Add(“Id”, “myhtmltab”);
tblgrid.Attributes.Add(“class”, “display”);
//We will use label control to add text to the table cell
Label lbl;
string previousText = “”;
int colSpan = 1;
for (cur_row = 0; cur_row < row_count; cur_row++)
{
//add new row to table
TableRow tr = new TableRow();
for (cur_col = 0; cur_col < col_count; cur_col++)
{
//create new cell and instance of label
TableCell td = new TableCell();
TableHeaderCell th = new TableHeaderCell();
lbl = new Label();
//check if we are writing to a ROW having column header
if (cur_row < col_dim_count)
{
//check if we are writing to a cell having row header
if (cur_col < row_dim_count)
{
//this should be empty cell — it’s on top left of the grid.
//result.Append(” ,”);
lbl.Text = ” “;
td.CssClass = “titleAllLockedCell”; //this locks
//the cell so it doesn’t scroll upwards nor leftwards
}
else
{
//this is a column header cell — use member caption for header
//result.Append(cst.Axes[0].Positions[cur_col –
// row_dim_count].Members[cur_row].Caption + “,”);
//if (cur_row < 1)
//{
lbl.Text = cst.Axes[0].Positions[cur_col – row_dim_count].Members[cur_row].Caption;
th.CssClass = “titleTopLockedCell”; // this lockeders
//the cell so it doesn’t scroll upwards
//}
if (lbl.Text == previousText)
{
colSpan++;
}
else
{
colSpan = 1;
}
}
}
else
{
//We are here.. so we are writing a row having data (not column headers)
//check if we are writing to a cell having row header
if (cur_col < row_dim_count)
{
//this is a row header cell — use member caption for header
lbl.Text = cst.Axes[1].Positions[cur_row –
col_dim_count].Members[cur_col].Caption.Replace(“,”, ” “);
td.CssClass = “titleLeftLockedCell”; // this lockeders
//the cell so it doesn’t scroll leftwards
}
else
{
//this is data cell.. so we write the Formatted value of the cell.
lbl.Text = cst[cur_col – row_dim_count, cur_row – col_dim_count].FormattedValue;
//td.InnerText = cst[cur_col – row_dim_count,
//cur_row – col_dim_count].FormattedValue;
td.CssClass = “valueCell”; //this right
//aligns the values in the column
}
//turn the wrapping off for row header and data cells.
td.Wrap = true;
}
if (((lbl.Text != previousText) || (lbl.Text == ” “))
&& (cur_row < col_dim_count))
{
tr.TableSection = TableRowSection.TableHeader;
th.Text = “HEADER”;
th.Controls.Add(lbl);
tr.Cells.Add(th);
tblgrid.Rows.Add(tr);
}
else if ((lbl.Text != previousText) || (lbl.Text == ” “) ||
(lbl.Text == null) || (lbl.Text == “”))
{
td.Controls.Add(lbl);
tr.Cells.Add(td);
tblgrid.Rows.Add(tr);
}
else
{
try
{
tr.Cells[tr.Cells.Count – 1].ColumnSpan = colSpan;
}
catch
{
}
}
if (cur_row < col_dim_count)
previousText = lbl.Text;
}
//result.AppendLine();
}
using (StringWriter writer = new StringWriter())
{
HtmlTextWriter htw = new HtmlTextWriter(writer);
tblgrid.RenderControl(htw);
return htw.InnerWriter.ToString();
}
}
catch (Exception ex)
{
throw ex;
}
[/csharp]

So it seems everything is set, now we have our html table, the controller will return this string to json, do you remember we have given the type as json in our ajax call?

[csharp]
return Json(readString, JsonRequestBehavior.AllowGet);
[/csharp]

Since our data is ready, we will re write our ajax function as follows.

[js]
$(‘#excelExport’).bind(‘click’, function (e) {
try {
$.ajax({
url: ‘../Exporting/Export/’,
type: ‘GET’,
dataType: ‘json’,
contentType: ‘application/json; charset=utf-8’,
success: function (data) {
data = ‘<div>’ + data + ‘</div>’;
var updateHtmlDom = $.parseHTML(data);
var AppliedHtml = updateHtmlDom[0].innerHTML;
AppliedHtml = tableToExcel(AppliedHtml, title + ".xls");
saveText($(‘#SubmitForm’), title + ".xls", AppliedHtml, ‘text/xls;charset=utf-8’);
},
error: function (xhrequest, ErrorText, thrownError) {
console.log(‘Excel Export Grid: ‘ + thrownError);
}

});
} catch (e) {
console.log(‘Excel Export Grid: ‘ + e.message);
}
});
[/js]

The first step we are doing is parsing the html we got by using $.parseHTML in jQuery. Next we are passing the parsed data to the the function tableToExcel so that the table can be formatted in the format of excel data. Here is the code for the function tableToExcel.

[js]
var tableToExcel = (function (table) {
var uri = ‘data:application/vnd.ms-excel;base64,’
, template = ‘<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!–[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines /></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]–></head><body><table>{table}</table></body></html>’
, base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
return function (table, name) {
var length = name.replace(‘.xls’, ”).length;
if (length > 30) {
name = name.slice(0, 25) + ‘…’;
}
else
name.replace(‘.xls’, ”);
var ctx = { worksheet: name || ‘Worksheet’, table: table }
return format(template, ctx)
}
})()
[/js]

Now we have formatted the html data to the one which excel supports. We are passing the data to the function saveText as follows.

[js]
saveText($(‘#SubmitForm’), title + ".xls", AppliedHtml, ‘text/xls;charset=utf-8’);
[/js]

Here title is the file name of the excel file to generated. The below is the definition of saveText function.

[js]
function saveText(ref, fname, text, mime) {
var blob = new Blob([text], { type: mime });
saveAs(blob, fname);
return false;
}
[/js]

Next we are going to export the data using blob export technology in HTML5.

If you are new to blog, you can check here Using blob to understand how to use it.

Everything is set now. Build your application and check the output now. Just click on the export button, I am sure an excel file will be downloaded.

The time taken for the exporting is completely depends on how many data your query returns. I suggest you to export maximum of 5000 for a query, so that it won’t affect any other process.

Excel Export In MDX

Excel Export In MDX

Conclusion

Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

Kindest Regards
Sibeesh Venu

Leave a Reply

Your email address will not be published. Required fields are marked *

Serverless 360