先将Excel导入到gridview再添加进数据库【Excel批量添加】
原文发布时间为:2008-10-27 —— 来源于本人的百度文章 [由搬家工具导入]
前台:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="导入Excle预览" />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="确定将以上数据导入数据库"
Visible="False" />
</form>
</body>
</html>
后台:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.IO;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string type1 = FileUpload1.PostedFile.ContentType;
string type = type1.Substring(type1.LastIndexOf("-") + 1, 5);
if (string.Equals(type, "excel"))
{
string newName = Server.MapPath("App_Data//Uploads//") + DateTime.Now.ToString("hhmmss") + ".xls";
FileUpload1.SaveAs(newName);
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + newName + ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(connStr);
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
OleDbDataAdapter oda = new OleDbDataAdapter("select * from [Sheet1$]", conn);
DataSet ds = new DataSet();
oda.Fill(ds);
conn.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
File.Delete(newName);
Session["paper"] = ds;
Button2.Visible = true;
}
else
{
Page.RegisterStartupScript("", "<script>alert('文件格式不正确')</script>");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
DataSet ds=(DataSet)Session["paper"];
SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;DataBase=master;Integrated Security=True");
if(conn.State.ToString()=="Closed")
{
conn.Open();
}
SqlCommand cmd = new SqlCommand();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string user = ds.Tables[0].Rows[i][0].ToString();
string paper = ds.Tables[0].Rows[i][1].ToString();
string score = ds.Tables[0].Rows[i][2].ToString();
string sql = "insert into [dbo].[paper]([user],[paper],[score]) values('" + user + "','" + paper + "','" + score + "')";
cmd.Connection = conn;
cmd.CommandText = sql;
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
Response.Write("插入失败!由于:"+ex.Message);
}
}
conn.Close();
Response.Write("<SCRIPT>alert('数据已成功导入到数据库!');</SCRIPT>");
}
}