1)使用vs2005新建个上传控件,然后就是判断是否是Excel文件(这里需要注意),如果是就可以新建个路径,然后把导入的Excel表保存到web站点的相关路径中(这里也需要注意因为我想在建立数据表时从这个路径的Excel表格导入)。
2)使用sql语句进行导入数据,这个导入方法微软官方提出了三种方法,我使用了第三种。具体实现可以从代码看出。
3)使用了微软的企业级类库
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data; using Microsoft.Practices.ObjectBuilder;
using System.Data.Common;
这个类库,得安装微软的类库,可以从微软官方网上搜出:Enterprise Library April 2007.msi 安装后可以通过解决方案右击引用相关的 EnterpriseLibrary.Common; EnterpriseLibrary.Data;类库就可以了;创建数据库对象。
再看看我的源代码!
web.config
<?xml version="1.0"?>
<!--
注意: 除了手动编辑此文件以外,您还可以使用
Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
“网站”->“Asp.Net 配置”选项。
设置和注释的完整列表在
machine.config.comments 中,该文件通常位于
\Windows\Microsoft.Net\Framework\v2.x\Config 中
-->
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data"/>
</configSections>
<connectionStrings>
<add name="publishSqlServer" providerName="System.Data.SqlClient" c/>
</connectionStrings>
<dataConfiguration defaultDatabase="publishSqlServer"/>
<system.web>
<!--
设置 compilation debug="true" 将调试符号插入
已编译的页面中。但由于这会
影响性能,因此只在开发过程中将此值
设置为 true。
-->
<compilation debug="true">
<assemblies>
<add assembly="System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Configuration.Install, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
<!--
通过 <authentication> 节可以配置 ASP.NET 使用的
安全身份验证模式,
以标识传入的用户。
-->
<authentication mode="Windows"/>
<!--
如果在执行请求的过程中出现未处理的错误,
则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,
开发人员通过该节可以配置
要显示的 html 错误页
以代替错误堆栈跟踪。
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
</configuration>
“Asp.Net 配置”选项。 设置和注释的完整列表在 machine.config.comments 中,该文件通常位于 \Windows\Microsoft.Net\Framework\v2.x\Config 中--> 节可以配置 ASP.NET 使用的 安全身份验证模式, 以标识传入的用户。 --> 节可以配置相应的处理步骤。具体说来, 开发人员通过该节可以配置 要显示的 html 错误页 以代替错误堆栈跟踪。 -->主要处理文件的代码:注意数据库sql语言,注意导入EXcle文件的路径。
FielUpload.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.ObjectBuilder;
using System.Data.Common;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if(FileUpload1 .PostedFile .ContentLength ==0||FileUpload1.PostedFile .FileName ==""||FileUpload1 .PostedFile ==null )
{
Response.Write("<script language='javascript'>alert('您可能选择的不是Excel文件。');</script>");
return;
}
string strFileName = "";
strFileName = this.FileUpload1.PostedFile.FileName;
//int intLastPoint = FileUpload1.PostedFile.FileName.LastIndexOf('.');
int intLastPoint = strFileName.LastIndexOf('.');
//if (!(intLastPoint > 0 && intLastPoint < (strFileName.Length - 1)))
if(!(intLastPoint >0&&intLastPoint<(strFileName .Length -3)))
{
Response.Write("<script language='javascrip'>alert('请选择Excel文件!');</script>");
return;
}
string strExtension = strFileName.Substring(intLastPoint ).ToLower() ;
if (strExtension != ".xls")
{
Response.Write("<script language='javascript'>alert('选择的文件不符合条件,你是否选择的是Excel表,请选择Excel文件!')</script>");
return;
}
//指定服务器上的存储的文件名
string strFileName2 = DateTime.Now.ToString("yyyymmddhhmmssff") + FileUpload1.PostedFile.ContentLength.ToString() + strExtension;
string strDataFilePath = Server.MapPath(Request.ApplicationPath + "
if (!System.IO.Directory.Exists(strDataFilePath))
{
System.IO.Directory.CreateDirectory(strDataFilePath);
}
string strDataFilePath2 = strDataFilePath + "\\" + strFileName2;
FileUpload1.PostedFile.SaveAs(strDataFilePath2);
if (!System.IO.File.Exists(strDataFilePath2))
{
Response.Write("<script language='javascript'>alert('这个文件的路径没有建立成功!')</script>");
return;
}
else
{
ViewState["DataFilePath"] = strDataFilePath2;
}
string strSQL = "";
Database db = DatabaseFactory.CreateDatabase();
try
{
strSQL = "if exists(select * from sysobjects where id=object_id('TempImportData1')) drop table TempImportData1";
DbCommand dbcommand = db.GetSqlStringCommand(strSQL);
db.ExecuteNonQuery(dbcommand);
strSQL = " SELECT * into TempImportData1";
strSQL += " FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0','Data Source=\"" + strDataFilePath2 + "\";User ID=Admin;Password=;Extended properties=Excel 8.0')...[Sheet1$]";
DbCommand dbcommand1 = db.GetSqlStringCommand(strSQL);
db.ExecuteNonQuery(dbcommand1);
}
catch
{
Response.Write("<script language='javascript'>alert('建立TempImportData表失败,可能权限不够,如果数据库是sql2005,更改配置工具中,SQL Server外围应用配置器中,功能的外围应用配置器,选中启用OPENROWSET和OPENDATASOURCE支持\n')</script>");
return;
}
Response.Write("<script language='javascript'>alert('导入Excel表格成功!')</script>");
}
}
下面我们再看看这个select into 语句的使用:
SELECT INTO
Name
SELECT INTO -- 从一个查询的结果中创建一个新表
Synopsis
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
* | expression [ AS output_name ] [, ...]
INTO [ TEMPORARY | TEMP ] [ TABLE ] new_table
[ FROM from_item [, ...] ]
[ WHERE condition ]
[ GROUP BY expression [, ...] ]
[ HAVING condition [, ...] ]
[ { UNION | INTERSECT | EXCEPT } [ ALL ] select ]
[ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ]
[ FOR UPDATE [ OF tablename [, ...] ] ]
[ LIMIT { count , ] { count | ALL } ]
[ OFFSET start ]
这里
from_item 可以是:
[ ONLY ] table_name [ * ]
[ [ AS ] alias [ ( column_alias_list ) ] ]
|
( select )
[ AS ] alias [ ( column_alias_list ) ]
|
from_item [ NATURAL ] join_type from_item
[ ON join_condition | USING ( join_column_list ) ]
输入
TEMPORARY
TEMP
如果声明了 TEMPORARY 或者 TEMP, 那么输出表就只在本次会话中创建,并且会话结束后自动删除. 同名的现存永久表在临时表存在期间将不可见(在本次会话中). 任何在临时表上创建的索引都是自动临时的.
new_table
要创建的新表名.这个表必须是尚未存在的. 不过,我们可以在存在一个永久表的情况下创建一个(同名)临时表.
所有其它输入的域都在 SELECT 中有详细描述.
输出
请参考 CREATE TABLE 和 SELECT 获取所有可能输出信息的摘要.
描述
SELECT INTO 从一个查询的计算结果中创建一个新表. 书局并不返回给客户端,这一点和普通的 SELECT 不同.新表的字段具有和 SELECT 的输出字段 相关联(相同)的名字和数据类型.
注意: CREATE TABLE AS 的作用和 SELECT INTO 相同. 我们建议使用 CREATE TABLE AS 语法, 因为 SELECT INTO 不是标准语法. 实际上,这种类型的 SELECT INTO 是不能在 PL/pgSQL或者 ecpg 中使用的, 因为它们对 INTO 子句的解释是不同的.
兼容性
SQL92 用 SELECT ... INTO 表示选取数值到一个 宿主程序的标量变量中,而不是创建一个新表. SQL92 的用法实际上就是在PL/pgSQL和 ecpg 里的用途. PostgreSQL 用 SELECT INTO 代表创建表的意思是历史原因.在新代码里我们 最好使用 CREATE TABLE AS 实现这个目地. (CREATE TABLE AS 也不是标准,但至少它 出现混淆的机会少一些.)
预祝你今天有个收获!!