<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>SSAS &#8211; Sibeesh Passion</title>
	<atom:link href="https://sibeeshpassion.com/tag/ssas/feed/" rel="self" type="application/rss+xml" />
	<link>https://sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:15:53 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>SSAS &#8211; Sibeesh Passion</title>
	<link>https://sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Find Datatype Of Each Measures In SSAS MDX Queries</title>
		<link>https://sibeeshpassion.com/find-datatype-of-each-measures-in-ssas-mdx-queries/</link>
					<comments>https://sibeeshpassion.com/find-datatype-of-each-measures-in-ssas-mdx-queries/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 22 Feb 2016 00:00:20 +0000</pubDate>
				<category><![CDATA[MDX Query]]></category>
		<category><![CDATA[SSAS]]></category>
		<category><![CDATA[Datatype Of Each Measures]]></category>
		<category><![CDATA[DMV Query]]></category>
		<category><![CDATA[MDX]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11226</guid>

					<description><![CDATA[In this post we will see how we can get the datatype of each measures we use in our SSAS MDX Queries. This post may be helpful if you are working with SSAS cubes especially you need to work with the data you gets from the cubes like formatting the data, assigning the data as grid data source or formulate the data to any other form. I have got a requirement to show the cube data as a grid, So I was needed to know the types of each measures user selects so that I can assign the grid column [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will see how we can get the datatype of each measures we use in our <a href="http://sibeeshpassion.com/category/ssas/" target="_blank">SSAS </a><a href="http://sibeeshpassion.com/category/microsoft-adomd/mdx-query/" target="_blank">MDX Queries</a>. This post may be helpful if you are working with SSAS cubes especially you need to work with the data you gets from the cubes like formatting the data, assigning the data as grid data source or formulate the data to any other form. I have got a requirement to show the cube data as a grid, So I was needed to know the types of each measures user selects so that I can assign the grid column types accordingly. There are few many ways we can find the types of measures, here I am going to discuss that with you. I hope you will like this. </p>
<p><strong>Background</strong></p>
<p>I had gone through this requirement and I could do this in time with the help of Mr.GregGalloway (Stack overflow user). You can find my question <a href="http://stackoverflow.com/questions/34528747/find-data-type-of-measures-in-cube-using-mdx-queries" target="_blank">here </a>in stack overflow. </p>
<p>If your cube has data with the types of string and numbers alone, finding the types will be too easy. Now before going through the processes listed in this article, if you don&#8217;t have only string and numbers as the types in the cube, this <a href="http://stackoverflow.com/questions/9951314/retrieving-data-type-of-measures-from-an-mdx-query-cellset-in-c-sharp" target="_blank">post </a>will definitely help you.</p>
<blockquote><p>If you are looking for some sample stored procedures that will help you with your development with your analysis services, you can always see it <a href="https://asstoredprocedures.codeplex.com/" target="_blank">here: ASSP &#8211; Analysis Services Stored Procedure Project</a>.
</p></blockquote>
<p><strong>Using the code</strong></p>
<p>Here we are going to create a function which accepts server name, database name, and the measure name collection in which we need to find out what type it is. The core part of this function will be a DMV query which we can run against our SSAS cube. The query will be as follows. </p>
<p>[sql]<br />
select [CATALOG_NAME],[CUBE_NAME],MEASURE_NAME, DATA_TYPE,EXPRESSION,MEASURE_IS_VISIBLE,MEASUREGROUP_NAME,MEASURE_DISPLAY_FOLDER,DEFAULT_FORMAT_STRING  from $system.mdschema_measures<br />
[/sql]</p>
<p>Now before going further, please make sure that you have included AnalysisServices Adomd Client.</p>
<p>[csharp]<br />
using Microsoft.AnalysisServices.AdomdClient;<br />
[/csharp]</p>
<p>Now we will create the function which will give you the data about the datatypes of your measures. </p>
<p>[csharp]<br />
#region Return the data types of measures<br />
        /// &lt;summary&gt;<br />
        /// FindMeasureDataTypes-Find the measure type whetehr it is a currency or a percentage or a number<br />
        /// &lt;/summary&gt;<br />
        /// &lt;param name=&quot;serverName&quot;&gt;&lt;/param&gt;<br />
        /// &lt;param name=&quot;databaseName&quot;&gt;&lt;/param&gt;<br />
        /// &lt;param name=&quot;myMeasureCollection&quot;&gt;&lt;/param&gt;<br />
        public DataTable FindMeasureDataTypes(string serverName, string databaseName, string myMeasureCollection)<br />
        {</p>
<p>            try<br />
            {<br />
                string res = string.Empty;<br />
                List&lt;string&gt; myMeasures = new List&lt;string&gt;();</p>
<p>                //Buiding the connection string start<br />
                StringBuilder sbConnectionString = new StringBuilder();<br />
                sbConnectionString.Append(&quot;Provider=MSOLAP;data source=&quot;);<br />
                sbConnectionString.Append(serverName + &quot;;initial catalog=&quot; + databaseName + &quot;;Integrated Security=SSPI;Persist Security Info=False;&quot;);<br />
                //Buiding the connection string start</p>
<p>                AdomdConnection conn = new AdomdConnection(sbConnectionString.ToString());<br />
                myMeasures = myMeasureCollection.Split(new string[] { &quot;||&quot; }, StringSplitOptions.None).ToList();</p>
<p>                for (int i = 0; i &lt; myMeasures.Count; i++)<br />
                {<br />
                    //Format the measure name<br />
                    if (i == 0)<br />
                        res += &quot;MEASURE_NAME =&#8217;&quot; + myMeasures[i].Replace(&quot;[Measures].&quot;, &quot;&quot;).Replace(&quot;[&quot;, &quot;&quot;).Replace(&quot;]&quot;, &quot;&quot;) + &quot;&#8217;&quot;;<br />
                    else<br />
                        res += &quot; OR MEASURE_NAME =&#8217;&quot; + myMeasures[i].Replace(&quot;[Measures].&quot;, &quot;&quot;).Replace(&quot;[&quot;, &quot;&quot;).Replace(&quot;]&quot;, &quot;&quot;) + &quot;&#8217;&quot;;<br />
                }</p>
<p>                string query = &quot;select [CATALOG_NAME],[CUBE_NAME],MEASURE_NAME, DATA_TYPE,EXPRESSION,MEASURE_IS_VISIBLE,MEASUREGROUP_NAME,MEASURE_DISPLAY_FOLDER,DEFAULT_FORMAT_STRING  from $system.mdschema_measures where &quot; + res;<br />
                using (AdomdCommand cmd = new AdomdCommand(query, conn))<br />
                {<br />
                    DataTable tblMeasureType = new DataTable();<br />
                    AdomdDataAdapter da = new AdomdDataAdapter(cmd);<br />
                    da.Fill(tblMeasureType);<br />
                    return tblMeasureType;<br />
                }</p>
<p>            }<br />
            catch (Exception)<br />
            {<br />
                return null;<br />
            }<br />
        }</p>
<p>        #endregion<br />
[/csharp]</p>
<p>So in the table <em>tblMeasureType</em>, we will get the data. In the column <em>DEFAULT_FORMAT_STRING </em>, you can see the actual type of your measure. It will show as &#8216;Currency&#8217; if it is a currency type and &#8216;Percentage&#8217; if it is a percentage type and &#8216;#,##&#8217; for the numbers. The <em>DEFAULT_FORMAT_STRING </em> actually describes each measures which are all available in the cube. And <em>DEFAULT_FORMAT_STRING </em>rowset contains the following columns. </p>
<li>CATALOG_NAME</li>
<li>SCHEMA_NAME</li>
<li>CUBE_NAME</li>
<li>MEASURE_NAME</li>
<li>MEASURE_UNIQUE_NAME</li>
<li>MEASURE_CAPTION</li>
<li>MEASURE_GUID</li>
<li>MEASURE_AGGREGATOR</li>
<li>DATA_TYPE</li>
<li>NUMERIC_PRECISION</li>
<li>NUMERIC_SCALE</li>
<li>MEASURE_UNITS</li>
<li>DESCRIPTION</li>
<li>EXPRESSION</li>
<li>MEASURE_IS_VISIBLE</li>
<li>LEVELS_LIST</li>
<li>MEASURE_NAME_SQL_COLUMN_NAME</li>
<li>MEASURE_UNQUALIFIED_CAPTION</li>
<li>MEASUREGROUP_NAME</li>
<li>MEASURE_DISPLAY_FOLDER</li>
<li>DEFAULT_FORMAT_STRING</li>
<p>You can always check <a href="https://msdn.microsoft.com/en-us/library/ms126250.aspx" target="_blank">here </a>to see for more information about <em>MDSCHEMA_MEASURES Rowset</em>.</p>
<p>As you can see the function accepts one parameter called <em>myMeasureCollection</em>, this is the collection of our measures and we are formatting the same as follows. </p>
<p>[csharp]<br />
 for (int i = 0; i &lt; myMeasures.Count; i++)<br />
                {<br />
                    //Format the measure name<br />
                    if (i == 0)<br />
                        res += &quot;MEASURE_NAME =&#8217;&quot; + myMeasures[i].Replace(&quot;[Measures].&quot;, &quot;&quot;).Replace(&quot;[&quot;, &quot;&quot;).Replace(&quot;]&quot;, &quot;&quot;) + &quot;&#8217;&quot;;<br />
                    else<br />
                        res += &quot; OR MEASURE_NAME =&#8217;&quot; + myMeasures[i].Replace(&quot;[Measures].&quot;, &quot;&quot;).Replace(&quot;[&quot;, &quot;&quot;).Replace(&quot;]&quot;, &quot;&quot;) + &quot;&#8217;&quot;;<br />
                }<br />
[/csharp]</p>
<p>The <em>myMeasureCollection</em> is a string variable which has the values in the format of [Measures].[My Measure 1]||[Measures].[My Measure 2]||[Measures].[My Measure 3]. That is why we are splitting the values with || as follows.</p>
<p>[csharp]<br />
 myMeasures = myMeasureCollection.Split(new string[] { &quot;||&quot; }, StringSplitOptions.None).ToList();<br />
[/csharp]</p>
<p>I hope everything is clear. Have a happy coding. </p>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>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.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/find-datatype-of-each-measures-in-ssas-mdx-queries/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Convert Data Reader To Datatable</title>
		<link>https://sibeeshpassion.com/convert-data-reader-to-datatable/</link>
					<comments>https://sibeeshpassion.com/convert-data-reader-to-datatable/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Tue, 17 Nov 2015 09:45:56 +0000</pubDate>
				<category><![CDATA[Microsoft ADOMD]]></category>
		<category><![CDATA[SSAS]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Data reader]]></category>
		<category><![CDATA[Data reader to Data table]]></category>
		<category><![CDATA[Generate table schema]]></category>
		<category><![CDATA[GetSchemaTable]]></category>
		<category><![CDATA[LoadDataRow]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10968</guid>

					<description><![CDATA[In this article we will learn how we can convert Microsoft ADOMD data reader to datatable. As you all know a data reader is the most efficient way for looping through the data. Performance wise a data reader is faster than any of the other way like data adapter and cell set in MDX result. So in few situations you may need to convert this data reader to a data table. Here in this post we will discuss how we can convert it. I hope you will like it. Background For the past few months I have been working with [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we will learn how we can convert Microsoft ADOMD data reader to datatable. As you all know a data reader is the most efficient way for looping through the data. Performance wise a data reader is faster than any of the other way like data adapter and cell set in MDX result. So in few situations you may need to convert this data reader to a data table. Here in this post we will discuss how we can convert it. I hope you will like it.</p>
<p><strong>Background</strong></p>
<p>For the past few months I have been working with Microsoft ADOMD data sources. And I have written some article also that will describe the problems I have encountered so far. If you are new to ADOMD I strongly recommend that read my previous articles that you may find useful when you work with ADOMD data sources. You can find those article links here: <a href="http://sibeeshpassion.com/category/microsoft-adomd/" target="_blank">ADOMD Data Sources </a></p>
<p><strong>Why </strong></p>
<p>You might think, why I am not using other two ways (data adapter and cell set). I will answer it here. I am handling large set of data, so when I use data adapter and cell set it was bit slow to get the output. So I was just checking the performance by using data reader. It was fast enough when I use data reader. So we can order these three as following by performance.</p>
<blockquote><p>Data reader >> Data Adapter >> Cell Set</p></blockquote>
<p><strong>Using the code</strong></p>
<p>The following is the function that does what was explained above.</p>
<p>[csharp]<br />
 #region Convert Datareader toDatatable<br />
        /// &lt;summary&gt;<br />
        /// Convert Datareader toDatatable<br />
        /// &lt;/summary&gt;<br />
        /// &lt;param name=&quot;query&quot;&gt;&lt;/param&gt;<br />
        /// &lt;param name=&quot;myConnection&quot;&gt;&lt;/param&gt;<br />
        public DataTable ConvertDataReaderToDataTable(string query, string myConnection)<br />
        {<br />
            AdomdConnection conn = new AdomdConnection(myConnection);<br />
            try<br />
            {<br />
                try<br />
                {<br />
                    conn.Open();<br />
                }<br />
                catch (Exception)<br />
                {<br />
                }<br />
                using (AdomdCommand cmd = new AdomdCommand(query, conn))<br />
                {<br />
                    AdomdDataReader rdr;<br />
                    cmd.CommandTimeout = connectionTimeout;<br />
                    using (AdomdDataAdapter ad = new AdomdDataAdapter(cmd))<br />
                    {<br />
                        DataTable dtData = new DataTable(&quot;Data&quot;);<br />
                        DataTable dtSchema = new DataTable(&quot;Schema&quot;);<br />
                        rdr = cmd.ExecuteReader();<br />
                        if (rdr != null)<br />
                        {<br />
                            dtSchema = rdr.GetSchemaTable();<br />
                            foreach (DataRow schemarow in dtSchema.Rows)<br />
                            {<br />
                                dtData.Columns.Add(schemarow.ItemArray[0].ToString(), System.Type.GetType(schemarow.ItemArray[5].ToString()));<br />
                            }<br />
                            while (rdr.Read())<br />
                            {<br />
                                object[] ColArray = new object[rdr.FieldCount];<br />
                                for (int i = 0; i &lt; rdr.FieldCount; i++)<br />
                                {<br />
                                    if (rdr[i] != null) ColArray[i] = rdr[i];<br />
                                }<br />
                                dtData.LoadDataRow(ColArray, true);<br />
                            }<br />
                            rdr.Close();<br />
                        }<br />
                        return dtData;<br />
                    }<br />
                }<br />
            }</p>
<p>            catch (Exception)<br />
            {<br />
                throw;<br />
            }<br />
            finally<br />
            {<br />
                conn.Close(false);<br />
            }<br />
        }<br />
        #endregion;<br />
[/csharp]</p>
<p>Here we are creating two data table dtData and dtSchema where dtData is for binding the data and dtSchema is for binding the schema.</p>
<p><em>Creating data tables</em></p>
<p>[csharp]<br />
 DataTable dtData = new DataTable(&quot;Data&quot;);<br />
                        DataTable dtSchema = new DataTable(&quot;Schema&quot;);<br />
[/csharp]</p>
<p><em>Execute data reader</em></p>
<p>Now we will execute the reader as follows.</p>
<p>[csharp]<br />
rdr = cmd.ExecuteReader();<br />
[/csharp]</p>
<p><em>Get the schema</em></p>
<p>To generate the schema, we can call the function GetSchemaTable() which is a part of your data reader.</p>
<blockquote><p>To use this function, you must include Microsoft.AnalysisServices.AdomdClient.dll</p></blockquote>
<p><em>Adding the columns headers to the dtData</em></p>
<p>The next thing is to add the header names to the data table dtData.</p>
<p>[csharp]<br />
foreach (DataRow schemarow in dtSchema.Rows)<br />
                            {<br />
                                dtData.Columns.Add(schemarow.ItemArray[0].ToString(), System.Type.GetType(schemarow.ItemArray[5].ToString()));<br />
                            }<br />
[/csharp]</p>
<p><em>Load the data to dtData </em></p>
<p>To load the data, we are using a function LoadDataRow() which expects an object as parameter. This will find and updates a specific row, if the matching row is not found, it will create an another row with the given values. </p>
<div id="attachment_10969" style="width: 608px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/11/Convert_data_reader_to_data_table.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-10969" src="http://sibeeshpassion.com/wp-content/uploads/2015/11/Convert_data_reader_to_data_table.png" alt="Convert data reader to data table" width="598" height="150" class="size-full wp-image-10969" srcset="/wp-content/uploads/2015/11/Convert_data_reader_to_data_table.png 598w, /wp-content/uploads/2015/11/Convert_data_reader_to_data_table-300x75.png 300w, /wp-content/uploads/2015/11/Convert_data_reader_to_data_table-400x100.png 400w" sizes="(max-width: 598px) 100vw, 598px" /></a><p id="caption-attachment-10969" class="wp-caption-text">Convert data reader to data table</p></div>
<p>[csharp]<br />
object[] ColArray = new object[rdr.FieldCount];<br />
                                for (int i = 0; i &lt; rdr.FieldCount; i++)<br />
                                {<br />
                                    if (rdr[i] != null) ColArray[i] = rdr[i];<br />
                                }<br />
                                dtData.LoadDataRow(ColArray, true);<br />
[/csharp]</p>
<p><strong>Conclusion</strong></p>
<p>Have you ever gone through this kind of requirement. Did I miss anything that you may think which is needed?. I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>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-Sharp Corner, Stack Overflow, Asp.Net Forums or Code Project instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I am able to.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/convert-data-reader-to-datatable/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Export MDX Result As Excel</title>
		<link>https://sibeeshpassion.com/export-mdx-result-as-excel/</link>
					<comments>https://sibeeshpassion.com/export-mdx-result-as-excel/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Wed, 28 Oct 2015 09:10:06 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MDX Query]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[ADOMD]]></category>
		<category><![CDATA[ADOMD CellSet]]></category>
		<category><![CDATA[Export CellSet in MVC]]></category>
		<category><![CDATA[Export In MDX]]></category>
		<category><![CDATA[Export MDX Result As Excel]]></category>
		<category><![CDATA[MDX]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[SSAS]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=10841</guid>

					<description><![CDATA[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 [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>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.</p>
<p>You can always read the about Microsoft ADOMD, MDX Queries and Cell Set here: <a href="http://sibeeshpassion.com/category/microsoft-adomd/" target="_blank" rel="noopener">Microsoft ADOMD,MDX,CellSet</a></p>
<p><strong>Background</strong></p>
<p>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. </p>
<p><strong>Using the code</strong></p>
<p>First of all you need to create a button in your page to fire the click event.</p>
<p>[html]<br />
 &lt;input type=&quot;submit&quot; class=&quot;exprotbutton&quot; value=&quot;Export to Excel&quot; id=&#8217;excelExport&#8217; /&gt;<br />
[/html]</p>
<p>Now you need to load the jQuery reference to the page.</p>
<p>[js]<br />
&lt;script src=&quot;Scripts/jquery-1.11.1.min.js&quot;&gt;&lt;/script&gt;<br />
[/js]</p>
<p>The next thing is to fire the click event.</p>
<p>[js]<br />
 $(&#8216;#excelExport&#8217;).bind(&#8216;click&#8217;, function (e) {<br />
        try {<br />
        } catch (e) {<br />
            console.log(&#8216;Excel Export Grid: &#8216; + e.message);<br />
        }<br />
    });<br />
[/js]</p>
<p>Now we will create an ajax call to our controller. </p>
<p>[js]<br />
$.ajax({<br />
                url: &#8216;../Exporting/Export/&#8217;,<br />
                type: &#8216;GET&#8217;,<br />
                dataType: &#8216;json&#8217;,<br />
                contentType: &#8216;application/json; charset=utf-8&#8217;,<br />
                success: function (data) {<br />
                },<br />
                error: function (xhrequest, ErrorText, thrownError) {<br />
                    console.log(&#8216;Excel Export Grid: &#8216; + thrownError);<br />
                }</p>
<p>            });<br />
[/js]</p>
<blockquote><p>Here Exporting is the controller name and Export is the action name</p></blockquote>
<p>Have you noticed that we have not created the action yet. No worries we will create it now.</p>
<p>[csharp]<br />
public JsonResult Export()<br />
        {<br />
            StringBuilder sbConnectionString = new StringBuilder();<br />
            sbConnectionString.Append(&quot;Provider=MSOLAP;data source=&quot;);<br />
            sbConnectionString.Append(serverName + &quot;;initial catalog=&quot; + databaseName + &quot;;Integrated Security=SSPI;Persist Security Info=False;&quot;);</p>
<p>            string readString = myModel.ExCellSet(query, sbConnectionString.ToString());<br />
            return Json(readString, JsonRequestBehavior.AllowGet);<br />
        }<br />
[/csharp]</p>
<blockquote><p> Here serverName, databaseName and query are the global variable I set. You can pass your own here.</p></blockquote>
<p>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?</p>
<p>[csharp]<br />
 public string ExCellSet(string query, string adoMDConnection)<br />
        {<br />
            string readerString = string.Empty;<br />
            CellSet cst = null;<br />
            AdomdConnection conn = new AdomdConnection(adoMDConnection);<br />
            try<br />
            {<br />
                try<br />
                {<br />
                    conn.Open();<br />
                }<br />
                catch (Exception){<br />
                }</p>
<p>                using (AdomdCommand cmd = new AdomdCommand(query, conn))<br />
                {<br />
                    cmd.CommandTimeout = connectionTimeout;<br />
                    cst = cmd.ExecuteCellSet();<br />
                }<br />
                if (cst.Axes != null)<br />
                {<br />
                    readerString = BuildHTML(cst);<br />
                    return readerString;<br />
                }<br />
                else<br />
                    return null;<br />
            }</p>
<p>            catch (Exception)<br />
            {<br />
                cst = null;<br />
                throw;<br />
            }<br />
            finally<br />
            {<br />
                conn.Close(false);<br />
                cst = null;<br />
            }<br />
        }<br />
[/csharp]</p>
<p>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: <a href="http://sibeeshpassion.com/convert-cellset-to-html-table-and-from-html-to-json-to-array/" target="_blank" rel="noopener">Convert CellSet to HTML Table</a></p>
<p>Anyway I am pasting the code here for your reference.</p>
<p>[csharp]</p>
<p>try<br />
            {<br />
                System.Text.StringBuilder result = new System.Text.StringBuilder();<br />
                //check if any axes were returned else throw error.<br />
                int axes_count = cst.Axes.Count;<br />
                if (axes_count == 0)<br />
                    throw new Exception(“No data returned for the selection”);<br />
                //if axes count is not 2<br />
                if (axes_count != 2)<br />
                    throw new Exception(“The sample code support only queries with two axes”);<br />
                //if no position on either row or column throw error<br />
                if (!(cst.Axes[0].Positions.Count &gt; 0) &amp;&amp; !(cst.Axes[1].Positions.Count &gt; 0))<br />
                    throw new Exception(“No data returned for the selection”);<br />
                int cur_row, cur_col, col_count, row_count, col_dim_count, row_dim_count;<br />
                cur_row = cur_col = col_count = row_count = col_dim_count = row_dim_count = 0;<br />
                //Number of dimensions on the column<br />
                col_dim_count = cst.Axes[0].Positions[0].Members.Count;<br />
                //Number of dimensions on the row<br />
                if (cst.Axes[1].Positions[0].Members.Count &gt; 0)<br />
                    row_dim_count = cst.Axes[1].Positions[0].Members.Count;<br />
                //Total rows and columns<br />
                row_count = cst.Axes[1].Positions.Count +<br />
                    col_dim_count;  //number of rows + rows for column headers<br />
                col_count = cst.Axes[0].Positions.Count +<br />
                    row_dim_count;  //number of columns + columns for row headers<br />
                //gridPanel.ClientIDMode = System.Web.UI.ClientIDMode.AutoID;<br />
                //////lets clear any controls under the grid panel<br />
                //gridPanel.Controls.Clear();<br />
                ////Add new server side table control to gridPanel<br />
                Table tblgrid = new Table();<br />
                tblgrid.Attributes.Add(“Id”, “myhtmltab”);<br />
                tblgrid.Attributes.Add(“class”, “display”);<br />
                //We will use label control to add text to the table cell<br />
                Label lbl;<br />
                string previousText = “”;<br />
                int colSpan = 1;<br />
                for (cur_row = 0; cur_row &lt; row_count; cur_row++)<br />
                {<br />
                    //add new row to table<br />
                    TableRow tr = new TableRow();<br />
                    for (cur_col = 0; cur_col &lt; col_count; cur_col++)<br />
                    {<br />
                        //create new cell and instance of label<br />
                        TableCell td = new TableCell();<br />
                        TableHeaderCell th = new TableHeaderCell();<br />
                        lbl = new Label();<br />
                        //check if we are writing to a ROW having column header<br />
                        if (cur_row &lt; col_dim_count)<br />
                        {<br />
                            //check if we are writing to a cell having row header<br />
                            if (cur_col &lt; row_dim_count)<br />
                            {<br />
                                //this should be empty cell — it’s on top left of the grid.<br />
                                //result.Append(” ,”);<br />
                                lbl.Text = ” “;<br />
                                td.CssClass = “titleAllLockedCell”; //this locks<br />
                                    //the cell so it doesn’t scroll upwards nor leftwards<br />
                            }<br />
                            else<br />
                            {<br />
                                //this is a column header cell — use member caption for header<br />
                                //result.Append(cst.Axes[0].Positions[cur_col –<br />
                                //    row_dim_count].Members[cur_row].Caption + “,”);<br />
                                //if (cur_row &lt; 1)<br />
                                //{<br />
                                    lbl.Text = cst.Axes[0].Positions[cur_col – row_dim_count].Members[cur_row].Caption;<br />
                                    th.CssClass = “titleTopLockedCell”; // this lockeders<br />
                                            //the cell so it doesn’t scroll upwards<br />
                                //}<br />
                                if (lbl.Text == previousText)<br />
                                {<br />
                                    colSpan++;<br />
                                }<br />
                                else<br />
                                {<br />
                                    colSpan = 1;<br />
                                }<br />
                            }<br />
                        }<br />
                        else<br />
                        {<br />
                            //We are here.. so we are writing a row having data (not column headers)<br />
                            //check if we are writing to a cell having row header<br />
                            if (cur_col &lt; row_dim_count)<br />
                            {<br />
                                //this is a row header cell — use member caption for header<br />
                                lbl.Text = cst.Axes[1].Positions[cur_row –<br />
                                col_dim_count].Members[cur_col].Caption.Replace(“,”, ” “);<br />
                                td.CssClass = “titleLeftLockedCell”; // this lockeders<br />
                                    //the cell so it doesn’t scroll leftwards<br />
                            }<br />
                            else<br />
                            {<br />
                                //this is data cell.. so we write the Formatted value of the cell.<br />
                                lbl.Text = cst[cur_col – row_dim_count, cur_row – col_dim_count].FormattedValue;<br />
                                //td.InnerText = cst[cur_col – row_dim_count,<br />
                                //cur_row – col_dim_count].FormattedValue;<br />
                                td.CssClass = “valueCell”; //this  right<br />
                                        //aligns the values in the column<br />
                            }<br />
                            //turn the wrapping off for row header and data cells.<br />
                            td.Wrap = true;<br />
                        }<br />
                        if (((lbl.Text != previousText) || (lbl.Text == ” “))<br />
                            &amp;&amp; (cur_row &lt; col_dim_count))<br />
                        {<br />
                            tr.TableSection = TableRowSection.TableHeader;<br />
                            th.Text = “HEADER”;<br />
                            th.Controls.Add(lbl);<br />
                            tr.Cells.Add(th);<br />
                            tblgrid.Rows.Add(tr);<br />
                        }<br />
                        else if ((lbl.Text != previousText) || (lbl.Text == ” “) ||<br />
                            (lbl.Text == null) || (lbl.Text == “”))<br />
                        {<br />
                            td.Controls.Add(lbl);<br />
                            tr.Cells.Add(td);<br />
                            tblgrid.Rows.Add(tr);<br />
                        }<br />
                        else<br />
                        {<br />
                            try<br />
                            {<br />
                                tr.Cells[tr.Cells.Count – 1].ColumnSpan = colSpan;<br />
                            }<br />
                            catch<br />
                            {<br />
                            }<br />
                        }<br />
                        if (cur_row &lt; col_dim_count)<br />
                            previousText = lbl.Text;<br />
                    }<br />
                    //result.AppendLine();<br />
                }<br />
                using (StringWriter writer = new StringWriter())<br />
                {<br />
                    HtmlTextWriter htw = new HtmlTextWriter(writer);<br />
                    tblgrid.RenderControl(htw);<br />
                    return htw.InnerWriter.ToString();<br />
                }<br />
            }<br />
            catch (Exception ex)<br />
            {<br />
                throw ex;<br />
            }<br />
[/csharp]</p>
<p>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?</p>
<p>[csharp]<br />
 return Json(readString, JsonRequestBehavior.AllowGet);<br />
[/csharp]</p>
<p>Since our data is ready, we will re write our ajax function as follows.</p>
<p>[js]<br />
  $(&#8216;#excelExport&#8217;).bind(&#8216;click&#8217;, function (e) {<br />
        try {<br />
            $.ajax({<br />
                url: &#8216;../Exporting/Export/&#8217;,<br />
                type: &#8216;GET&#8217;,<br />
                dataType: &#8216;json&#8217;,<br />
                contentType: &#8216;application/json; charset=utf-8&#8217;,<br />
                success: function (data) {<br />
                    data = &#8216;&lt;div&gt;&#8217; + data + &#8216;&lt;/div&gt;&#8217;;<br />
                    var updateHtmlDom = $.parseHTML(data);<br />
                    var AppliedHtml = updateHtmlDom[0].innerHTML;<br />
                    AppliedHtml = tableToExcel(AppliedHtml, title + &quot;.xls&quot;);<br />
                    saveText($(&#8216;#SubmitForm&#8217;), title + &quot;.xls&quot;, AppliedHtml, &#8216;text/xls;charset=utf-8&#8217;);<br />
                },<br />
                error: function (xhrequest, ErrorText, thrownError) {<br />
                    console.log(&#8216;Excel Export Grid: &#8216; + thrownError);<br />
                }</p>
<p>            });<br />
        } catch (e) {<br />
            console.log(&#8216;Excel Export Grid: &#8216; + e.message);<br />
        }<br />
    });<br />
[/js]</p>
<p>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.</p>
<p>[js]<br />
var tableToExcel = (function (table) {<br />
    var uri = &#8216;data:application/vnd.ms-excel;base64,&#8217;<br />
, template = &#8216;&lt;html xmlns:o=&quot;urn:schemas-microsoft-com:office:office&quot; xmlns:x=&quot;urn:schemas-microsoft-com:office:excel&quot; xmlns=&quot;http://www.w3.org/TR/REC-html40&quot;&gt;&lt;head&gt;&lt;!&#8211;[if gte mso 9]&gt;&lt;xml&gt;&lt;x:ExcelWorkbook&gt;&lt;x:ExcelWorksheets&gt;&lt;x:ExcelWorksheet&gt;&lt;x:Name&gt;{worksheet}&lt;/x:Name&gt;&lt;x:WorksheetOptions&gt;&lt;x:DisplayGridlines /&gt;&lt;/x:WorksheetOptions&gt;&lt;/x:ExcelWorksheet&gt;&lt;/x:ExcelWorksheets&gt;&lt;/x:ExcelWorkbook&gt;&lt;/xml&gt;&lt;![endif]&#8211;&gt;&lt;/head&gt;&lt;body&gt;&lt;table&gt;{table}&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;&#8217;<br />
, base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }<br />
    , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }<br />
    return function (table, name) {<br />
        var length = name.replace(&#8216;.xls&#8217;, &#8221;).length;<br />
        if (length &gt; 30) {<br />
            name = name.slice(0, 25) + &#8216;&#8230;&#8217;;<br />
        }<br />
        else<br />
            name.replace(&#8216;.xls&#8217;, &#8221;);<br />
        var ctx = { worksheet: name || &#8216;Worksheet&#8217;, table: table }<br />
        return format(template, ctx)<br />
    }<br />
})()<br />
[/js]</p>
<p>Now we have formatted the html data to the one which excel supports. We are passing the data to the function saveText as follows.</p>
<p>[js]<br />
saveText($(&#8216;#SubmitForm&#8217;), title + &quot;.xls&quot;, AppliedHtml, &#8216;text/xls;charset=utf-8&#8217;);<br />
[/js]</p>
<p>Here title is the file name of the excel file to generated. The below is the definition of saveText function.</p>
<p>[js]<br />
function saveText(ref, fname, text, mime) {<br />
    var blob = new Blob([text], { type: mime });<br />
    saveAs(blob, fname);<br />
    return false;<br />
}<br />
[/js]</p>
<p>Next we are going to export the data using blob export technology in HTML5. </p>
<blockquote><p>If you are new to blog, you can check here <a href="http://sibeeshpassion.com/compress-xml-string-variables-in-client-side-and-export-in-html5-using-jquery/" target="_blank" rel="noopener">Using blob</a> to understand how to use it.
</p></blockquote>
<p>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.</p>
<blockquote><p>
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&#8217;t affect any other process.
</p></blockquote>
<div id="attachment_10843" style="width: 332px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2015/10/Excel_Export_In_MDX.png"><img decoding="async" aria-describedby="caption-attachment-10843" src="http://sibeeshpassion.com/wp-content/uploads/2015/10/Excel_Export_In_MDX.png" alt="Excel Export In MDX" width="322" height="251" class="size-full wp-image-10843" srcset="/wp-content/uploads/2015/10/Excel_Export_In_MDX.png 322w, /wp-content/uploads/2015/10/Excel_Export_In_MDX-300x234.png 300w" sizes="(max-width: 322px) 100vw, 322px" /></a><p id="caption-attachment-10843" class="wp-caption-text">Excel Export In MDX</p></div>
<p><strong>Conclusion</strong></p>
<p>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.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>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.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/export-mdx-result-as-excel/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
