您的位置首页生活快答

怎么把excel或word表导入数据表再读取出来

怎么把excel或word表导入数据表再读取出来

的有关信息介绍如下:

怎么把excel或word表导入数据表再读取出来

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 System.Data.OleDb;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

SqlDataSource1.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

}

protected void Button2_Click(object sender, EventArgs e)

{

string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

try

{

//求取要导入的excel表地址

string FileUrl = TypeName(FileUpload1);

DataSet ds = new DataSet();

//把excel表中的数据读取到数据集里

ds = xsldata(FileUrl);

//创建数据库批量copy对象bcp

SqlBulkCopy bcp = new SqlBulkCopy(constr);

//确定数据copy的目的地

bcp.DestinationTableName = "UserInfo";

// 把数据集里的数据一次性添加到对应的数据库表中

bcp.WriteToServer(ds.Tables);

Response.Write("alert('数据导入成功!');");

}

catch (Exception ex)

{

Response.Write("插入失败!由于:" + ex.Message);

}

}

//检测导入文件是否正确,返回excel文件地址

private String TypeName(FileUpload Fileloads)

{

string murl = "";

//获取要导入的excel文件绝对地址

string fullfilename = Fileloads.PostedFile.FileName;

//求取文件类型

string type = fullfilename.Substring(fullfilename.LastIndexOf(".") + 1);

//判断文件类型是否正确

if (type == "xls")

{

murl = fullfilename.ToString();

}

else

{

Response.Write("alert('导入文件格式不对!');");

}

return murl;

}

//根据excel文件的路径把excel表中的数据读取到数据集里

private DataSet xsldata(string filepath)

{

//编写excel表数据连接字串

string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;IMEX=1'";

OleDbConnection Conn= new OleDbConnection(strCon);

//编写查询excel表查询语句

string strCom = "SELECT * FROM [Sheet1$]";

//建立与excel表的连接

Conn.Open();

//创建数据填充适配器对象myAdpCommand

OleDbDataAdapter myAdpCommand = new OleDbDataAdapter(strCom, Conn);

//临时创建数据集ds

DataSet ds = new DataSet();

//将数据填充到数据集ds中

myAdpCommand.Fill(ds, "[Sheet1$]");

Conn.Close();

//函数返回填充过数据的数据集

return ds;

}

protected void Button1_Click(object sender, EventArgs e)

{

//编写数据库查询语句查询用户表里的数据

string MySqlStr = "select * from UserInfo";

//给数据源的查询指令复制

SqlDataSource1.SelectCommand = MySqlStr;

//给Gridview1绑定数据源,显示查询数据

GridView1.DataSourceID = SqlDataSource1.ID;

}

}

------------------------------------------------

这是我们做的把excel导入到数据库,然后显示出来,把里面的一些表名什么的改一下就行了,你看看副不符合你要求,。需要一个fileupload控件,一个gridview控件,两个button控件(一个是确定按钮,一个是显示数据的按钮。)。