1. 在web设计页面中,设计成如下的界面(包括2个label,1个fileupload,1个dropdownlist,2个按钮)。首先点击“浏览”,选择要上传的excel表格路径,然后点击“查看数据”,在dropdownlist中显示excel中的所有表名,选择要上传的表明,点击“导入”,则可将选定表的数据导入到数据库中。
2. 具体代码:
static string path;//定义路径
protected void Page_Load(object sender, EventArgs e)
{
}
//导入选定的excel指定的工作表
protected void Button1_Click(object sender, EventArgs e)
{
//确定导入的总的工程数量
int countContract = 0;
if (path == "")//如果路径为空
{
Response.Write("");
}
else//路径不为空
{
try
{
string mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + path + "';Extended Properties=Excel 8.0";
OleDbConnection cnnxls = new OleDbConnection(mystring);
OleDbDataAdapter myDa = new OleDbDataAdapter("select * from ["+DropDownList1 .SelectedItem.Text .ToString ().Trim ()+"]", cnnxls);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
//excel中有记录的话
if (myDs.Tables[0].Rows.Count > 0)
{
string strSql = "";
string CnnString = "Provider=SQLOLEDB;database=brcm;server=(local);uid=sa;pwd=sa";
OleDbConnection conn = new OleDbConnection(CnnString);
conn.Open();
OleDbCommand myCmd = null;
#region//导入excel

这篇博客介绍了如何使用ASP.NET实现从Excel表格上传并将其数据导入到SQL Server数据库的过程。用户通过文件上传选择Excel文件,系统读取文件中的表名,用户选择表后,代码将数据插入到指定的数据库表中。在导入过程中,还会检查是否存在重复项,避免数据冲突。
最低0.47元/天 解锁文章
201

被折叠的 条评论
为什么被折叠?



