65.9K
CodeProject 正在变化。 阅读更多。
Home

将 CellSet 转换为 HTML 表格,并从 HTML 转换为 Json、数组

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.06/5 (6投票s)

2015 年 2 月 27 日

CPOL

3分钟阅读

viewsIcon

16086

将 CellSet 转换为 HTML 表格,并从 HTML 转换为 Json、数组

引言

由于过去几天我一直在研究 ADOMD 和 MDX,我遇到了一个需要将我的 CellSet 转换为 HTML 表格并在客户端网格中呈现的情况。 因此,我想与大家分享一下。

这篇文章被选为 2014 年 11 月 10 日星期一的当日文章,来自 http://www.asp.net/community/articles (将 CellSet 转换为 HTML 表格,并从 HTML 转换为 Json、数组)

背景

如果您是 ADOMD 新手,可以参考以下链接

  1. https://codeproject.org.cn/Articles/28290/Microsoft-Analysis-Services-Displaying-a-grid
  2. http://www.microsoft.com/msj/0899/mdx/mdx.aspx

为什么?

正如我在当前项目中已经说过的那样,我们正在使用 MDX 多维数据集,因此在服务器端我们只会得到 CellSet。 因此,我尝试了很多次将 CellSet 转换为 Json,仅用于这个 JQX 网格(项目中的所有其他网格都使用 HTML 表格作为数据源)。 但我找不到任何好方法。 所以我考虑从服务器端的其他网格中获取 CellSet 中的 HTML 表格。 而且我知道我们如何从 HTML 表格中制定数组和 Json。 在这里,我分享这些信息。

请提供您宝贵的改进建议。

Using the Code

我们根据上述文章中的要求修改了代码,并将其绑定到 HtmlTextWriter。 我们创建了一个名为 renderHTML() 的函数,它将接受 CellSet 作为参数。 在这里,我将粘贴代码。

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;
            }

最后,该函数将返回一个 HTML 表格作为输出,id 为 “myhtmltab”,其中所有 thtrtd 都会被渲染。

现在,如果您愿意,您可以在客户端将 HTML 表格转换为数组、Json。

现在我们需要做的就是将动态 HTML 添加到 DOM 中。 您可以按如下方式操作

 $('#your element id').html(data); 

请在此处阅读更多信息:https://api.jqueryjs.cn/html/

在 Jquery 中动态地将 HTML 转换为数组

假设您有一个 Ajax Jquery 函数,它将返回我已在输出图像中显示的内容。

如果您不熟悉 Jquery Ajax 函数,请在此处阅读

然后在 Ajax 函数的成功回调中,您可以编写如下代码来制定一个数组。

接下来是从您使用 CellSet 刚刚制定的动态 HTML 表格中获取列和行

var rows = $("#myhtmltab tbody tr"); //Select Rows , looping through every tr

var columns = $("#myhtmltab thead th"); //Select columns , looping through every th

现在我们需要一个可以填充数据的数组。 Smile | :)

var data = [];
for (var i = 0; i < rows.length; i++) {
    var row = rows[i];
    var datarow = {};
    for (var j = 0; j < columns.length; j++) {
        // get column's title.
        var columnName = $.trim($(columns[j]).text());
        // select cell.
        var cell = $(row).find('td:eq(' + j + ')');
        datarow[columnName] = $.trim(cell.text());
    }
    data[data.length] = datarow;
}

现在是时候从您的表格中制定一个 Json 了。 Smile | :)

在 Jquery 中动态地将动态 HTML 转换为 Json

正如我们上面讨论的那样,在这里我们也循环遍历列和行。 这样做的目的是制定动态 Json 以将数据分配给我的 JQX 网格(您可以在 此处查看)。

var varDataFields = '[';
var varDataColumns = '[';
var typ = 'string';
var align = 'center';
var width = '200';

var myColumns = $("#myhtmltab thead th");
for (var j = 0; j < myColumns.length; j++) {
    var column = myColumns[j];
    var col = $(column).text().trim();
    //col = col.replace('<span>', '');
    //col = col.replace('</span>', '');
    //var col = $(columns).find('th:get(' + j + ').find(' < span > ').text()');
    //if (!col == '') {
    varDataFields = varDataFields + 
    ' { \"name\" : \"' + col + '\" , \"type\" : \"' + typ + '\"},';
    varDataColumns = varDataColumns + 
    ' { \"text\" : \"' + col + '\" , \"dataField\" :  \"' + 
    col + '\" , \"align\" :  \"' + align + '\" , \"width\" : \"' + width + '\"},';
    //}
    
    if (j == myColumns.length - 1) {
        varDataFields = varDataFields.slice(0, -1);
        varDataColumns = varDataColumns.slice(0, -1)
    }
}
varDataFields = varDataFields + ']';
varDataColumns = varDataColumns + ']';
varDataFields = varDataFields.trim();
varDataColumns = varDataColumns.trim();

var DataFields = $.parseJSON(varDataFields);
var DataColumns = $.parseJSON(varDataColumns);

因此,在 DataFieldsDataColumns 中,我将以我想要的方式获取 json。 我可以直接将其绑定到 JQX 网格。 Smile | :)

关注点

  • ADOMD, MDX
© . All rights reserved.