uploadfy导入Excel内容到数据库中

aspx: 
<script src="/Content/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> 
<script src="/Content/Scripts/swfobject.js" type="text/javascript"></script> 
<script src="/Content/Scripts/jquery.uploadify.v2.1.0.min.js" type="text/javascript"></script> 
<link href="/Content/Styles/uploadify.css" rel="stylesheet" type="text/css" /> 


<div style="float:left; width:280px"> 
                <input type="file" name="uploadify" id="uploadify" /> 
                <p> &nbsp; 
                <a charset="utf-8" href="javascript:startUpload()">开始上传</a> &nbsp;| &nbsp; 
                <a charset="utf-8" href="javascript:cancelUpload()">取消上传</a> 
                </p> 
            </div> 
            <div style=" width:100%; height:36px;"> 
                <div id="fileQueue" style="text-align:left;"></div> 
            </div> 
            <div style="width:100%;" id ="divImportP"> 
                <img src="/Content/images/large-loading.gif" alt="加载中.." style=" display:block; float:left; width:32px; height:32px;" /> 
                <div style="color:#999900; float:left; margin-left:4px">导入数据处理中,请稍侯,请勿关闭本对话框,完成后会自动关闭.</div> 
            </div> 




js: 
var uploadSizeLimit = 30242880; 


        $("#uploadify").uploadify({ 
            'uploader': '/Content/jquery/up/uploadify.swf', 
            'script': 'DoImport', 
            'scriptData': { uploadtype: 'selCustom', q_t: $("#txtCustom").text() }, 
            'cancelImg': '/Content/jquery/up/cancel.png', 
            'folder': '', 
            'sizeLimit': uploadSizeLimit, 
            'queueID': 'fileQueue', 
            'method ': 'POST', 
            'auto': true, 
            'multi': false, 
            'fileExt': '*.xls;*.xlsx;',  //'*.*'表示所有类型的文件 
            'fileDesc': '请选择Excel文件(*.xls,*.xlsx)', 
            onSelect: function (event, queueID, fileObj) { 
                var size = parseInt(fileObj.size); 
                if (size > uploadSizeLimit) { 
                    alert("对不起,文件大小超过限制(30M),请重新选择"); 
                    g_filesize = 0; 
                    cancelUpload(); 
                    return false; 
                } 
                $('#divImportP').removeClass('Hide'); 
                $('#uploadify').uploadifySettings('scriptData', { uploadtype: 'CustomQR', q_t: $("#txtCustom").val() }); 
            }, 
            onError: function (event, queueId, fileObj, errorObj) { 
                alert("上传失败: " + errorObj.info); 
            }, 
            onCancel: function (event, queueId, fileObj, data) { 
            }, 
            onComplete: function (event, queueId, fileObj, response, data) { 
                
                var result = eval("(" + response + ")"); 
                if (result.result < 0) { 
                    alert(result.data); 
                } else { 
                    alert("上传成功"); 
                } 
            } 
        }); 

function startUpload() { 
    $('#uploadify').uploadifyUpload(); 


function cancelUpload() { 
    $('#uploadify').uploadifyClearQueue(); 
}



cs:(上传文件并将Excel中的内容导入到数据库中) 
public JsonResult DoImport(string uploadtype, string q_t) 
        { 
            iPAL.Applications.Authen.LoginUser user = (iPAL.Applications.Authen.LoginUser)(Session["LoginUser"]); 
            m_userno = user.WorkNo; 

            AjaxCallResult result = new AjaxCallResult(); 

            HttpContext.Response.ContentType = "text/plain"; 
            HttpContext.Response.Charset = "utf-8"; 

            string msg = string.Empty; 
            string strUploadPath = HttpContext.Request.PhysicalApplicationPath + "iPALUploads\\"; 
            try 
            { 
                if (!Directory.Exists(strUploadPath)) 
                { 
                    Directory.CreateDirectory(strUploadPath); 
                } 
                if ( HttpContext.Request.Files.Count != 1 ) 
                { 
                    result.result = -1; 
                    result.data = "上传文件只能为1."; 
                    return Json(result); 
                } 
                HttpPostedFileBase postedFile = HttpContext.Request.Files[0]; 
                string fileName = postedFile.FileName; 
                string ext = fileName.Substring(fileName.LastIndexOf('.')); 
                string tempFile = fileName.Substring(0,fileName.Length - ext.Length -1 ) +  Guid.NewGuid().ToString("N"); 
                tempFile = Path.Combine(strUploadPath, tempFile) + ext; 
                postedFile.SaveAs(tempFile); 

                result.result = ImportSheet(tempFile, q_t, m_userno, ref msg); 
                result.data = msg; 

            } 
            catch (Exception ex) 
            { 

                result.result = -1; 
                result.data = ex.Message; 
            } 

            return Json(result); 
        } 
        private int ImportSheet(string filePath,string bigT,string userno,ref string msg) 
        { 
            ExcelReader excel = new ExcelReader(); 
            DataTable dt = new DataTable(); 
            int nRet = 0; 
            List<BIGT_SHEET_MODEL> lstSheet = btModuel.GetSheetModel();//sheet 
            List<BIGT_SHEET_MODEL> lstColModel = btModuel.GetColModel();//列模型 
            List<BigTColModel> lstCol = new List<BigTColModel>(); 

            BIGT_SHEET_MODEL col; 
            BIGT_SHEET_MODEL sheet; 

            int nFailSheet = 0; 
            for( int i=0; i < lstSheet.Count;i++) 
            { 
                sheet = lstSheet[i]; 
                if (excel.ReadFromExcel(filePath, sheet.sheet_name, dt) < 0) 
                { 
                    nFailSheet++; 
                    if (nFailSheet == lstSheet.Count) 
                    { 
                        msg = "没有发现任何可识别Sheet名"; 
                        return -1; 
                    } 
                    continue; 
                } 
                //获取列模型 
                lstCol.Clear(); 
                for (int k = 0; k < lstColModel.Count; k++) 
                { 
                    col = lstColModel[k]; 
                    if (string.IsNullOrEmpty(col.col_index))//只取与数据库对应的列 
                    { 
                        continue; 
                    } 
                    if (string.IsNullOrEmpty(col.col_model) || sheet.col_model == col.col_model) 
                    { 

                        BigTColModel colModel = new BigTColModel(); 
                        colModel.sheet_name = col.sheet_name; 
                        colModel.col_index = col.col_index; 

                        lstCol.Add(colModel); 
                    } 
                    else 
                    { 
                        continue; 
                    } 
                } 

                nRet = ImportSheetData(userno, sheet.sheet_name, bigT, dt, lstCol, ref msg); 
                if (nRet < 0) 
                { 
                    return -1; 
                } 
            } 
            
            return 1; 
        }



private int ImportSheetData(string userno, string sheet, string bigT, DataTable dt, List<BigTColModel> lstColModel, ref string msg) 
        { 
            BigTColModel COL; 
            /**********   查找列表头对应的列序号   *******/ 
            DataRow drTitle2 = dt.Rows[0];//二级表头 
            string colName, colName2; 
            bool bColOver = false; 
            for (int i = 1; i < dt.Columns.Count; i++)//第0列为序号 
            { 
                if (bColOver) 
                { 
                    break;//最后一列 
                } 
                colName = CommonMethod.toString(dt.Columns[i]); 
                colName2 = CommonMethod.toString( drTitle2[i] ); 
                if (colName == string.Empty && colName2 == string.Empty) 
                { 
                    continue; 
                } 
                for (int k = 0; k < lstColModel.Count; k++) 
                { 
                    COL = lstColModel[k]; 
                    if (colName != COL.sheet_name && colName2 != COL.sheet_name) 
                    { 
                        continue; 
                    } 

                    lstColModel[k].col_pos = i;//记录对应的列索引 
                    if (k == lstColModel.Count - 1) 
                    { 
                        bColOver = true;//最后一列,因为lstColModel是按列大小排序的 
                    } 
                } 
            } 

            /**********   导入数据   *******/ 
            DataRow dr; 
            int indexNum=0; 
            for (int i = 1; i < dt.Rows.Count; i++)//从第一列开始 
            { 
                dr = dt.Rows[i]; 
                if (CommonMethod.toInt(dr[0], ref indexNum) <= 0) 
                { 
                    break;//序号为空,空行,跳出 
                } 

                //采集一行的数据 
                for (int k = 0; k < lstColModel.Count; k++) 
                { 
                    COL = lstColModel[k]; 
                    if (string.IsNullOrEmpty(COL.col_index) || COL.col_pos <= 0) //没有对应数据库表对应列,没有对应Excel对应列 
                    { 
                        continue;// 
                    } 
                    lstColModel[k].col_data = CommonMethod.toString(dr[COL.col_pos]); //赋值 
                } 

                if (btModuel.InsertRowData(userno, sheet, bigT, lstColModel) < 0) 
                { 
                    msg = btModuel.m_sMsg; 
                    return -1; 
                } 
            } 
            return 1; 
        }



public int ReadFromExcel(string fileName, string sheetName, System.Data.DataTable dataTable) 
        { 
            OleDbConnection connection = new System.Data.OleDb.OleDbConnection(); 
            try 
            { 
                string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=YES\""; 
                string sql = "SELECT * FROM  [" + sheetName + "$]"; 

                connection = new OleDbConnection(connectionString); 
                connection.Open(); 

                OleDbCommand command = new OleDbCommand(sql, connection); 
                OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command); 
                DataSet excelOriginalData = new DataSet(); 

                dataTable.Columns.Clear(); 
                dataTable.Clear(); 

                dataAdapter.Fill(dataTable); 
            } 
            catch (Exception e) 
            { 
                m_sMsg = e.Message; 
                return -1; 
            } 
            finally 
            { 
                if (connection.State != System.Data.ConnectionState.Closed) 
                { 
                    connection.Close(); 
                } 
                connection.Dispose(); 
            } 
            return 1; 
        }

你可能感兴趣的:(upload)