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 on 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 on client side. Simple right? Then let us move on. I hope you will like this article.
You can always read 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
Firstly, you need to create a button in your page to fire the click event.
- <input type="submit" class="exprotbutton" value="Export to Excel" id='excelExport'/>
Now you need to load the jQuery reference to the page.
- <script src="Scripts/jquery-1.11.1.min.js"></script>
The next thing is to fire the click event.
- $('#excelExport').bind('click', function (e)
- {
- try
- {}
- catch (e)
- {
- console.log('Excel Export Grid: ' + e.message);
- }
- });
Now we will create an Ajax call to our controller.
- $.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);
- }
- });
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.
- 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);
- }
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?
- 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;
- }
- }
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.
- try
- {
- System.Text.StringBuilder result = new System.Text.StringBuilder();
-
- int axes_count = cst.Axes.Count;
- if (axes_count == 0) throw new Exception(“No data returned
- for the selection”);
-
- if (axes_count != 2) throw new Exception(“The sample code support only queries with two axes”);
-
- 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;
-
- col_dim_count = cst.Axes[0].Positions[0].Members.Count;
-
- if (cst.Axes[1].Positions[0].Members.Count > 0) row_dim_count = cst.Axes[1].Positions[0].Members.Count;
-
- row_count = cst.Axes[1].Positions.Count + col_dim_count;
- col_count = cst.Axes[0].Positions.Count + row_dim_count;
-
-
-
-
- Table tblgrid = new Table();
- tblgrid.Attributes.Add(“Id”, “myhtmltab”);
- tblgrid.Attributes.Add(“class”, “display”);
-
- Label lbl;
- string previousText = “”;
- int colSpan = 1;
- for (cur_row = 0; cur_row < row_count; cur_row++)
- {
-
- TableRow tr = new TableRow();
- for (cur_col = 0; cur_col < col_count; cur_col++)
- {
-
- TableCell td = new TableCell();
- TableHeaderCell th = new TableHeaderCell();
- lbl = new Label();
-
- if (cur_row < col_dim_count)
- {
-
- if (cur_col < row_dim_count)
- {
-
-
- lbl.Text = ”“;
- td.CssClass = “titleAllLockedCell”;
-
- }
- else
- {
-
-
-
-
-
- lbl.Text = cst.Axes[0].Positions[cur_col– row_dim_count].Members[cur_row].Caption;
- th.CssClass = “titleTopLockedCell”;
-
-
- if (lbl.Text == previousText)
- {
- colSpan++;
- }
- else
- {
- colSpan = 1;
- }
- }
- }
- else
- {
-
-
- if (cur_col < row_dim_count)
- {
-
- lbl.Text = cst.Axes[1].Positions[cur_row– col_dim_count].Members[cur_col].Caption.Replace(“, ”, ”“);
- td.CssClass = “titleLeftLockedCell”;
-
- }
- else
- {
-
- lbl.Text = cst[cur_col– row_dim_count, cur_row– col_dim_count].FormattedValue;
-
-
- td.CssClass = “valueCell”;
-
- }
-
- 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;
- }
-
- }
- using(StringWriter writer = new StringWriter())
- {
- HtmlTextWriter htw = new HtmlTextWriter(writer);
- tblgrid.RenderControl(htw);
- return htw.InnerWriter.ToString();
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
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?
- return Json(readString, JsonRequestBehavior.AllowGet);
Since our data is ready, we will rewrite our Ajax function as follows.
- $('#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);
- }
- });
The first step we are doing is parsing the html we got using $.parseHTML in jQuery. Next we are passing the parsed data to the function tableToExcel so that the table can be formatted in the format of excel data. Here is the code for the function tableToExcel.
- 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)
- {
- returnc[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)
- }
- })()
Now we have formatted the html data to the one which excel supports. We are passing the data to the function saveText as follows.
- saveText($('#SubmitForm'), title + ".xls", AppliedHtml, 'text/xls;charset=utf-8');
Here title is the file name of the excel file to be generated. The following is the definition of saveText function.
- function saveText(ref, fname, text, mime) {
- var blob = new Blob(1, { type: mime });
- saveAs(blob, fname);
- return false;
- }
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 exporting 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.
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?
If you have any questions, then please mention in the comments section.
Please see this article in my blog
here.