在WEB项目开发过程中有时会碰到批量插入数据到数或者是将EXCEL文件据入到数据库中.为了方便实现可以先将EXCEL导入到GRIDVIEW中然后一次批量插入.实现代码如下:
前台代码
后台代码:
//首先在命名空间中加入以下两行
using System.Data.SqlClient;
using System.Data.OleDb;
protected void btn2_Click(object sender, EventArgs e)
{
string filepath = FileUpload1.PostedFile.FileName;
ReadExcel(filepath, dgBom);
}
public void ReadExcel(string sExcelFile, GridView dgBom)
{
DataTable ExcelTable;
DataSet ds = new DataSet();
//Excel的连接
OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sExcelFile + ";" + "Extended Properties=Excel 8.0;");
objConn.Open();
DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
string tableName = schemaTable.Rows[0][2].ToString().Trim();//获取 Excel 的表名,默认值是sheet1
string strSql = "select * from [" + tableName + "]";
OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
OleDbDataAdapter myData = new OleDbDataAdapter(strSql, objConn);
myData.Fill(ds, tableName);//填充数据
dgBom.DataSource =ds;
dgBom.DataBind();
objConn.Close();
ExcelTable = ds.Tables[tableName];
int iColums = ExcelTable.Columns.Count;//列数
int iRows = ExcelTable.Rows.Count;//行数
//定义二维数组存储 Excel 表中读取的数据
string[,] storedata = new string[iRows, iColums];
for(int i=0;i
for (int j = 0; j < ExcelTable.Columns.Count; j++)
{
//将Excel表中的数据存储到数组
storedata[i, j] = ExcelTable.Rows[i][j].ToString();
}
int excelBom = 0;//记录表中有用信息的行数,有用信息是指除去表的标题和表的栏目,本例中表的用用信息是从第三行开始
//确定有用的行数
for (int k = 2; k < ExcelTable.Rows.Count; k++)
if (storedata[k, 1] != "")
excelBom++;
if (excelBom == 0)
{
Response.Write("");
}
else
{
//LoadDataToDataBase(storedata,excelBom)//该函数主要负责将 storedata 中有用的数据写入到数据库中,在此不是问题的关键省略
}
}
protected void btninsert_Click(object sender, EventArgs e)
{
foreach (GridViewRow gv in dgBom.Rows)
{
//我的连接字符串是写在WEB.CONFIG中的.
string con = System.Configuration.ConfigurationManager.AppSettings["ConnectionString1"].ToString();
SqlConnection conn = new SqlConnection(con);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into student (studentnumber,studentname) values(@studentnumber,@studentname)";
cmd.Parameters.Add("@studentnumber", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("@studentname", SqlDbType.NVarChar, 10);
cmd.Parameters["@studentname"].Value = ((TextBox)gv.FindControl("studentname")).Text;
cmd.Parameters["@studentnumber"].Value = ((TextBox)gv.FindControl("studentnumber")).Text;
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
finally
{
if (conn != null)
conn.Dispose();
}
}
}
以上内容就是本文的全部叙述,希望对大家学习C#.NET中如何批量插入大量数据到数据库中有所帮助。