主要解决Excel导入数据库

页面上的JS脚本 判断浏览器 选择文件的绝对路径 

 1 <script type="text/javascript">
 2             function checkFile()
 3             {
 4                 //判断浏览器类型
 5                 var isIE = (document.all) ? true : false;
 6                 var isIE7 = isIE && (navigator.userAgent.indexOf('MSIE 7.0') != -1);
 7                 var isIE8 = isIE && (navigator.userAgent.indexOf('MSIE 8.0') != -1);
 8          
 9                 var file=document.getElementById("FileUpload1");
10                 var path=file.value;
11                 
12                 if(isIE7 || isIE8)
13                 {
14                     file.select();
15                     path=document.selection.createRange().text;
16                     document.selection.empty();
17                 }
18                document.getElementById("txtFilePath").value=path;
19             }
20             function checkNull()
21             {
22                var path=document.getElementById("txtFilePath").value;
23                if(path=="" ||path==null)
24                {
25                 alert('请选择要上传的文件!');
26                 return false;
27                }
28                return true;
29             }
30         </script> 
View Code

  网页中需要如下控件:

<asp:FileUpload ID="FileUpload1" runat="server" onchange="checkFile()" />

<input type="hidden" id="txtFilePath" runat="server" />

后台导入:

 1 /// <summary>
 2    /// Excel导入数据库操作确认
 3    /// </summary>
 4    /// <param name="sender"></param>
 5    /// <param name="e"></param>
 6     protected void Button2_Click(object sender, EventArgs e)
 7     {
 8         string str = txtFilePath.Value.Trim(); ///JS脚本实现获取文件的绝对路径
 9         ///string str = FileUpload1.PostedFile.FileName;///IE6以前版本获取文件路径字符串
10         ///Excel表插入数据库操作语句
11         string strInsert = "insert into Student select StuId,StuPwd,StuName,StuZhuanYe ,StuCardId,TeaName "+
12                            "from OPENROWSET('MICROSOFT.JET.OLEDB.4.0','Excel 8.0;IMEX=1;HDR=YES;DATABASE="+ str +"',[Sheet1$])";
View Code
原文地址:https://www.cnblogs.com/zxd543/p/3079502.html