Apply Excel in ASP. NET: (10) generate an HTML table on the client [Correction]

Source: Internet
Author: User

This section describes how to generate an HTML table on the server. To implement this function on the client, you need to use the ScriptMethod method to return the XmlDocument to the client. The client uses the JavaScript script to complete table rendering.

First, implement the WebService on the server, which is assumed to be ReadDataService. asmx. Its implementation is roughly as follows:

Using System. xml; using System. xml ;... /// <summary> // Summary description for MyService // </summary> [WebService (Namespace = "http://tempuri.org/")] [WebServiceBinding (ConformsTo = WsiProfiles. basicProfile1_1)] [ScriptService] public class ReadDataService: System. web. services. webService {[WebMethod] [ScriptMethod (ResponseFormat = ResponseFormat. xml)] public XmlDocument read (string excelFile) // directly use The file name is used as a parameter. Other parameters, such as id, should be used in actual applications. Otherwise, security issues may occur. {XmlDocument xml = new XmlDocument (); xml. LoadXml ("<? Xml version =/"1.0/" encoding =/"UTF-8/"?> <Data> </Data> "); // The xml filling process is omitted.. return xml; // result }...}

You also need to add a reference to WebService on the page, or you can add it to MasterPage:

<ajaxToolkit:ToolkitScriptManager ID="ScriptManager1" runat="server" >    <Services>            <asp:ServiceReference  Path="ReadDataService.asmx" />        </Services></ajaxToolkit:ToolkitScriptManager>

In this way, the WebService method is called through a JavaScript script on the client:

ReadDataService.read(onReadDataSucceeded, onReadDataFailed, 'xmlDocument');

Onreaddatasucceeded and onreaddatafailed process the call success and failure events respectively. When the table is generated successfully, a prompt is displayed:

// Result is the result returned by the server // context is the specified context. Here, 'xmldocument' // methodName is read, and our ReadDataService. the name of the read method function onReadDataSucceeded (result, context, methodName) {readTicks = getMilliseconds ()-readTicks; // The time is now within 10 seconds, in my example, it is generally between 7.3-7.5 seconds // alert ('time consumption: '+ (readTicks/1000.0) + 'seconds'); if (document. all) // IE {for (var sheet_idx = 0; sheet_idx <result.doc umentElement. childNodes. l Ength; sheet_idx ++) // traverse the worksheet {var sheet_node = result.doc umentElement. childNodes [sheet_idx]; // worksheet node var _ rowNum = 1, // Number of worksheet columns _ colNum = 1, sheetName = ''; // worksheet name var table = document. createElement ('table'); // create a new TABLE. id = 'sheet _ '+ sheet_idx; // table name // set the cell style table. style. borderCollapse = 'collapse'; table. style. tableLayout = 'fixed'; table. style. border = '1px solid black'; // you can specify the cell attribute tab. Le. cellPadding = 0; table. cellSpacing = 0; for (var attr_idx = 0; attr_idx <sheet_node.attributes.length; attr_idx ++) {var attr = sheet_node.attributes [attr_idx]; switch (attr. nodeName) {case 'name': sheetName = attr. nodeValue; break; case 'width': table. style. width = attr. nodeValue + 'pt'; break; // width case 'row': _ rowNum = parseInt (attr. nodeValue); break; // row, number of columns case 'col': _ colNum = parseInt (Attr. nodeValue); break;} // Add the worksheet to document if (document. sheet) document. sheet [document. sheet] = {'table': table. id, 'name': sheetName}; else document. sheet = [{'table': table. id, 'name': sheetName}]; // worksheet name var sheetNameRow = table. insertRow (); var sheetNameCell = sheetNameRow. insertCell (); initHeaderCell (sheetNameCell); sheetNameCell. colSpan = _ colNum + 1; sheetNameCell. innerText = sh EetName; sheetNameCell. style. width = table. style. width; // Add the column header var colHeaderRow = table. insertRow (); for (var col_idx = 0; col_idx <= _ colNum; col_idx ++) {var cell = colHeaderRow. insertCell (); // col_idx); if (col_idx> 0) cell. innerText = getColLabel (col_idx); else cell. innerText = ''; // the first cell! InitHeaderCell (cell) ;}for (var row_idx = 0; row_idx <sheet_node.childNodes.length; row_idx ++) // traverse rows {var row = table. insertRow () // row_idx + 1); // insert row {// insert row header var rowHeaderCell = row. insertCell (); // 0); initHeaderCell (rowHeaderCell); rowHeaderCell. innerText = row_idx + 1; // row. rowIndex;} var row_node = sheet_node.childNodes [row_idx]; // row node for (var attr_idx = 0; attr_idx <row_node.attributes.length; attr_idx ++)/traverse attributes, set the Row Height {var attr = row_node.attributes [attr_idx]; // obtain the row attribute switch (attr. nodeName) {case "height": row. height = attr. nodeValue; break; // height} if (row_node.childNodes.length = 0) // No cell, it is a blank row {for (var I = 1; I <= _ colNum; I ++) // insert an empty cell {initEmptyCell (row. insertCell (); // I) ;}} else for (var cell_idx = 0; cell_idx <row_node.childNodes.length; cell_idx ++) // traverse the column {var cell_node = row_node.childNodes [cell_idx]; // cell node var prev_cell_node = cell_node.previussibling; // previous node var cellProp = {// cell attribute 'row ': 0, 'col': 0, 'rowspan ': 1, 'colsize': 1, 'hasformula': false, 'formula': '', 'value2 ':'', 'weight': '', 'height':'', 'font-family ': '', 'font-size':'', 'font-color ': '', 'font-bold ': false, 'font-italic': false, 'font-strikethrough ': false, 'align':'', 'valign ': ''};
// Obtain the cell attributes for (VAR attr_idx = 0; attr_idx <cell_node.attributes.length; attr_idx ++) {var ATTR = cell_node.attributes [attr_idx]; procellp [ATTR. nodename] = ATTR. nodevalue;} // The data parsed from XML will become a string, so you need to change it to number. Otherwise, cellprop will fail after completing the plan below. col = parseint (cellprop. COL); cellprop. rowspan = parseint (cellprop. rowspan); cellprop. colspan = parseint (cellprop. colspan); If (prev_cell_node) // if the previous node exists, you may need to complete the intermediate blank {var prevco1_x = 0, // The unit number of the previous node and prevcolspan = 1;

 

For (VAR attr_idx = 0; attr_idx <prev_cell_node.attributes.length; attr_idx ++) // obtain the attributes of the previous cell
{
VaR ATTR = prev_cell_node.attributes [attr_idx];

Switch (attr. nodeName)
{
Case 'col': prevcoint x = parseInt (attr. nodeValue); break; // column number
Case 'colspan ': prevColSpan = parseInt (attr. nodeValue); break; // column Span
}
}

If (prevco1_x + prevColSpan <cellProp. col) // if the center is empty, insert
{
For (var I = prevcow.x + prevColSpan; I <cellProp. col; I ++)
{
InitEmptyCell (row. insertCell (); // I); // fill the empty hole
}
}
}
Else
{
If (cellprop. Col> 1) // if the number of cells is not 1st (the column header starts from 0), complete
{
For (VAR I = 1; I <cellprop. Col; I ++)
Initemptycell (row. insertcell (I); // fill the empty hole
}
}

// Insert a cell
Var cell = row. insertCell ();

// Set attributes
Cell. align = cellProp. align;
Cell. valign = cellProp. valign;
Cell. width = cellProp. width;
Cell. height = cellProp. height;
Cell. style. color = cellProp ['font-color'];
Cell. style. fontFamily = cellProp ['font-family '];
Cell. style. fontSize = cellProp ['font-size'];
Cell. style. fontweight = cellprop ['font-bold '] = 'true '? 'Bold ':'';
Cell. style. Border = '1px solid black ';
Cell. colspan = cellprop. colspan;
Cell. _ rowspan = cellprop. rowspan;

// Set the data domain
Cell. hasFormula = cellProp. hasFormula;
Cell. formula = cellProp. formula;
Cell. dataField = cell. innerText = cellProp. value2;

// If no subsequent node exists, it indicates the last cell. At this time, it needs to be completed to have _ colNum columns.
If (cell_node.nextSibling = null & cellProp. col + cellProp. colspan <= _ colNum)
{
For (var I = cellProp. col + cellProp. colspan; I <= _ colNum; I ++)
InitEmptyCell (row. insertCell (); // I); // insert an empty cell
}
} // For cell
} // For row

Setallcelltip (table );

Document. Body. appendchild (table );
} // For Sheet
}
Else
{// Firefox
// Stay with students for homework
}
}

 

Function onReadDataFailed (error) // a processing error is prompted.
{
Var stackTrace = error. get_stackTrace ();
Var message = error. get_message ();
Var statusCode = error. get_statusCode ();
Var exceptionType = error. get_exceptionType ();
Var timedout = error. get_timedOut ();

// Display the error.
Alert ("Stack Trace:" + stackTrace + "<br/>" +
"Service Error:" + message + "<br/>" +
"Status Code:" + statusCode + "<br/>" +
"Exception Type:" + exceptionType + "<br/>" +
"Timedout:" + timedout );}

So far, the client has finished generating tables.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.