基本原理是将excel文件读取放入DataSet中,然后将DataSet中表的数据添加到sql的数据表中
aspx文件代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register src="webpartDropdownlist.ascx" tagname="webpartDropdownlist" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fName" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="导入" onclick="Button1_Click" />
<br />
<br />
</div>
</form>
</body>
</html>
CS文件代码
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string fPath = this.fName.PostedFile.FileName;//获得要导入的文本文件
string extName = fPath.Substring(fPath.LastIndexOf(".") + 1);//获得文件的扩展名
//SqlConnection con = new SqlConnection("server=.;database=pubs;uid=sa;pwd=sa;");//数据库连接对象
//con.Open();
string mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + fPath + "';Extended Properties=Excel 8.0";
OleDbConnection cnnxls = new OleDbConnection(mystring);
OleDbDataAdapter myDa = new OleDbDataAdapter("select * from [Sheet1$]", cnnxls);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
if (myDs.Tables[0].Rows.Count > 0)
{
string strSql = "";
string CnnString = "Provider=SQLOLEDB;database=pubs;server=.;uid=sa;pwd=sa";
OleDbConnection conn = new OleDbConnection(CnnString);
conn.Open();
OleDbCommand myCmd = null;
for (int i = 0; i < myDs.Tables[0].Rows.Count; i++)//第一个工作表中行数,不包括第一行,
{
strSql = "insert into txtInsert(id,name) values (";
strSql += myDs.Tables[0].Rows[i].ItemArray[0].ToString() + ", '";
strSql += myDs.Tables[0].Rows[i].ItemArray[1].ToString() + "')";
myCmd = new OleDbCommand(strSql, conn);
try
{
myCmd.ExecuteNonQuery();
Response.Write("<script language=javascript>alert('数据导入成功!')</script>");
}
catch (OleDbException err)
{
Response.Write("导入数据库时出错:" + err.ToString());
break;
}
}
conn.Close();
}
}
}
pubs数据库中txtInsert表结构
Excel文件中的数据
如果想把Excel表里的第一行的数据也写入加个 HDR=No
string mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + fPath + "';Extended Properties='Excel 8.0;HDR=No;IMEX=1'";