Summary of Web Development Framework experience based on MVC4 + EasyUI (10) -- data import and export on the Web interface, mvc4easyui
Data import and export are common in many systems. This Import and Export Operation is easy to implement in Winform, I used to introduce the design and development process of the general import and export module in Winform in the previous article "Winform development framework-general data import and export operations, but how should we implement it on the Web? This article mainly introduces the features of MVC4 + EasyUI, combined with the use of the file upload control Uploadify, the process of processing and displaying the file after uploading, and then writing the data into the database after confirmation.
We know that the processing of Excel on the Web is different from that of Winform. If it is processed on the Web, we need to upload the Excel document to the server and then read the file for display, therefore, the first step is to upload files, for more information, see my article "Creating a Web development framework based on MVC4 + EasyUI-how to use the attachment Upload Component uploadify".
1. display the imported data interface
In Winform, the following figure shows the process of importing Excel Data.
The main interface on the Web is as follows.
The import interface is as follows.
2. Web data import processing logic and code
To import and export data on the Web, we need to add two buttons: Import button and export button.
<A href = "javascript: void (0)" class = "easyui-linkbutton" id = "btnImport" iconcls = "icon-excel" onclick = "ShowImport () "> Import </a> <a href =" javascript: void (0) "class =" easyui-linkbutton "id =" btnExport "iconcls =" icon-excel "onclick =" ShowExport () "> export </a>
The imported JS processing code is as follows.
// Display the import interface function ShowImport () {$. showWindow ({title: 'customer Contact-Excel Data import', useiframe: true, width: 1024, height: 700, content: 'url:/Contact/import', buttons: [{text: 'cancel', iconCls: 'icon-cancel', handler: function (win) {win. close () ;}}]});}
The preceding window is used to conveniently select an Excel file, save data, or download an import template.
In the view code of Import. cshtml, We need to initialize the Datagrid and related interface elements. The code for initializing the DataGrid is as follows.
// Function InitGrid () {var guid = $ ("# AttachGUID") to bind the initird control "). val (); $ ('# grid '). datagrid ({// locate the Table tag. The Table tag ID is grid url: '/Contact/GetExcelData? Guid = '+ guid, // point to the background Action to obtain the data title of the current user's information in Json format: 'customer contact-Excel Data import', iconCls: 'icon-view', height: 400, width: function () {return document. body. clientWidth * 0.9}, // automatic width ..................
The red part above initializes the list data of the DataGrid Based on the guid parameter when the file is successfully uploaded to the server.
The following is the initialization script code of the attachment upload control uploadify. In the red part, note that we need to upload a file and do not allow multiple selections. the type of the uploaded file is limited to xls.
After the file is uploaded, call the CheckExcelColumns controller function to check whether the fields of the imported template match. If the fields match, load the Excel file and display the data to the Datagrid, otherwise, you are prompted to enter data in the template format.
<Script type = "text/javascript"> $ (function () {// Add an attachment management interface $ ('# file_upload '). uploadify ({'swf ':'/Content/JQueryTools/uploadify/uploadify.swf ', // path of the FLash file 'buttontext': 'browsed', // button text 'upload ': '/FileUpload/upload', // process the ASHX page 'queue id': 'filequee', // queue ID 'queue size': 1, // The maximum number of files that can be uploaded in the queue, the default value is 999 'auto': false. // if the file is automatically uploaded after the file is selected, the default value is true 'multi ': false. // if multiple files are selected, the default value is true 'removecompleted ': true, // Yes If no, the sequence is removed. The default value is true 'filesizelimmit ': '10mb'. // the size of a single file. The value 0 indicates no limit. The sequence size is KB, MB, and acceptable, 'filetypedesc': 'excel Files ', // file description 'filetypeexists ':'*. xls ', // the filename suffix filter 'onqueuecomplete': function (event, data) {// event var guid =$ ("# AttachGUID") After all queues are completed "). val (); ViewUpFiles (guid, "div_files"); // The system prompts you whether the Excel format is normal. If the data is loaded normally $. ajax ({url: '/Contact/CheckExcelColumns? Guid = '+ guid, type: 'get', ype: 'json', success: function (data) {if (data. success) {InitGrid (); // refresh table data $. messager. alert ("prompt", "File Uploaded, data loaded! ");} Else {$. messager. alert (" prompt "," The uploaded Excel file fails to be checked. Enter data according to the Excel template format in the upper-right corner of the page. ") ;}}) ;}, 'Onuploadstart': function (file) {InitUpFile (); // reset the GUID before uploading a file, different $ ("# file_upload") each time "). uploadify ("settings", 'formdata', {'folder': 'Data import file', 'guid': $ ("# AttachGUID "). val ()}); // dynamically passing parameters}, 'onuploaderror': function (event, queueId, fileObj, errorObj) {// alert (errorObj. type + ":" + errorObj.info );}});});
In order to effectively process the data import, we must strictly ensure that the imported data matches the template fields. Otherwise, processing is prone to errors and makes no sense. In order to achieve this purpose, the Framework provides methods to check fields, mainly to ensure that the Excel file contains a complete field.
/// <Summary> /// check whether the fields in the Excel file contain the required fields. /// </summary> /// <param name = "guid"> GUID </param> /// <returns> </returns> public ActionResult CheckExcelColumns (string guid) {CommonResult result = new CommonResult (); try {DataTable dt = ConvertExcelFileToTable (guid); if (dt! = Null) {// check whether the list contains the required field result. success = DataTableHelper. containAllColumns (dt, columnString) ;}} catch (Exception ex) {LogTextHelper. error (ex); result. errorMessage = ex. message;} return ToJsonContent (result );}
The GetExcelData Controller Method in InitGrid Initialization is as follows. The main logic is to obtain the Excel file, convert the data in the Excel file to the DataTable file, initialize it to the object class list, and return it to the call page.
/// <Summary> /// obtain the Excel file on the server, convert the Object List and return it to the client // </summary> /// <param name = "guid"> attachment GUID </param> /// <returns> </returns> public ActionResult GetExcelData (string guid) {if (string. isNullOrEmpty (guid) {return null;} List <ContactInfo> list = new List <ContactInfo> (); DataTable table = ConvertExcelFileToTable (guid); if (table! = Null) {# region data conversion int I = 1; foreach (DataRow dr in table. rows) {string customerName = dr ["customer name"]. toString (); if (string. isNullOrEmpty (customerName) {continue; // The Customer name is empty, record skipped} CustomerInfo customerInfo = BLLFactory <Customer>. instance. findByName (customerName); if (customerInfo = null) {continue; // The customer name does not exist, record skipped} ContactInfo info = new ContactInfo (); info. customer_ID = customerInfo. ID; // customer ID info. handNo = dr ["no."]. toString (); info. name = dr ["Name"]. toString ();.............................. // Add the escape info for a special field. data1 = BLLFactory <Customer>. instance. getCustomerName (info. customer_ID); list. add (info) ;}# endregion} var result = new {total = list. count, rows = list}; return JsonDate (result );}
3. Export Web Data
I just introduced the data import operation. The data export operation is relatively simple. Its JS function operations are as follows.
// Export Excel Data var exportCondition; function ShowExport () {var url = "/Contact/Export"; $. ajax ({type: "POST", url: url, data: exportCondition, success: function (filePath) {var downUrl = '/FileUpload/DownloadFile? File = '+ filePath; window. location = downUrl ;}});}
Although data export is simpler, since we need to use the POST method to submit data conditions, it is not like the normal method to download the file Window. open (url) to download the file. If parameters are submitted in POST mode, the returned data cannot be effectively downloaded even if it is a file stream.
From the above script, we can see that exportCondition is the condition for us to submit to the server. The server retrieves data based on this condition and returns an Excel file.
Because the POST method such as ajax cannot directly download the file stream, We need to generate a file on the server according to the conditions and return a file path, download the file again using the DownloadFile method.
Therefore, the transfer condition is also very important. During the query operation, we can pass the corresponding condition to it.
// BindSearchEvent () {// click the event function BindSearchEvent () bound to the search button to query data by conditions. First, we get the data value $ ("# btnSearch "). click (function () {// you can obtain the user-input parameters. // you can set the value to $ ("# id "). combobox ('getvalue'), $ ("# id "). datebox ('getvalue'), $ ("# id "). val (), combotree ('getvalue') // Add the WHC _ prefix to the field to avoid Request keyword conflict such as URL var queryData = {WHC_Name: $ ("# txtName "). val (), WHC_OfficePhone: $ ("# txtOfficePhone "). val (), WHC_Mobile: $ ("# txtMobile "). val (), WHC_Address: $ ("# txtAddress "). val (), WHC_Email: $ ("# txtEmail "). val (), WHC_Note: $ ("# txtNote "). val ()} // pass the value to the DataGrid InitGrid (queryData); // pass the value to the Export OperationExportCondition = queryData;Return false ;});}
When we select a node of a tree, we can also pass custom conditions to it.
// Load the specified list function loadByGroupTree (node) based on the message group {// assign a value to a special field, select a var queryParams =$ ('# grid') When querying the company and department '). datagrid ('options '). queryParams; var condition = "{id: \" "+ node. id + "\", groupname: \ "" + node. text + "\", userid: \ "" + @ Session ["UserId"] + "\"} "; queryParams. customedCondition = condition; // conditions provided to the datagridExportCondition = {CustomedCondition: condition };// Conditions provided for export $ ("# grid"). datagrid ("reload"); $ ('# grid'). datagrid ('uncheckall ');}
The main logic of the background Export Controller method is as follows.
Finally, a generated file address is returned.
Finally, you can download the file directly using a method.
/// <Summary> /// download the object based on the path, download the generated file /// </summary> /// <param name = "filePath"> file path </param> /// <returns> </returns> public ActionResult DownloadFile (string file) {string realPath = Server. mapPath (file); string saveFileName = FileUtil. getFileName (realPath); Response. writeFile (realPath); Response. charset = "GB2312"; Response. contentEncoding = Encoding. getEncoding ("GB2312"); Response. contentType = "application/ms-excel/msword"; Response. appendHeader ("Content-Disposition", "attachment; filename =" + HttpUtility. urlEncode (saveFileName); Response. flush (); Response. end (); return new FileStreamResult (Response. outputStream, "application/ms-excel/msword ");}
The exported Excel interface is as follows.
Due to the length of the article, this import and export operation will be introduced here, and we hope you will discuss some issues together.
Which team is the strongest in Live 8?
Webserver implementation in embedded systems: Which web development framework should be selected for web interface development?
I don't know what you want to ask. Isn't the management interface similar to vro for embedded systems, such as most network equipment products?