原文发布时间为: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>
        &nbsp;<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>");
    }
}

先将Excel导入到gridview再添加进数据库【Excel批量添加】的更多相关文章

  1. Web安全--使用Salt + Hash将密码加密后再存储进数据库

    转载原地址 http://www.bozhiyue.com/mianshiti/_net/2016/0728/314239.html (一) 为什么要用哈希函数来加密密码 如果你需要保存密码(比如网站 ...

  2. Java使用Mysql数据库实现批量添加数据

    EmployeeDao.java //批处理添加数据 public int saveEmploeeBatch(){ int row = 0; try{ con = DBCon.getConn(); S ...

  3. dedecms--后台添加会员栏目(批量添加)

    最近在用dedecms二次开发会员功能,一开始做了一个会员添加,但是领导要求可以批量添加,最好是可以输入添加个数:这样我想添加几个就添加几个了 1:会员添加的htm页面 <html> &l ...

  4. ASP.NET Aries 高级开发教程:Excel导入之单表配置(上)

    前言: 随着ASP.NET Aries的普及,刚好也有点闲空,赶紧把Excel导入功能的教程补上. Excel导入功能,分为四篇:单表配置(上).多表高级配置(中).配置规则(下).代码编写(番外篇) ...

  5. excel导入工具

    1 介绍 excel导入工具 整个项目的代码结构如下 \---excelExport # 导出工具包 | AsyncExportExcel.java #多线程导出 | ExcelImport.java ...

  6. Excel导入工具类

    项目需要从Excel导入数据,然后插入到数据库对应表中.设计了一个导入工具类,导入数据和导入结果如下图示: poi jar版本采用的3.15 导入工具类实现如下: package com.alphaj ...

  7. php Excel 导入

    php Excel 导入 public function storeSql() { $file = input('file.excel'); $path = ROOT_PATH . 'public' ...

  8. spring MVC 后端 接收 前端 批量添加的数据(简单示例)

    第一种方式:(使用ajax的方式) 前端代码: <%@ page contentType="text/html;charset=UTF-8" language="j ...

  9. Crowd 批量添加用户(Postman 数据驱动)

    背景 最近公司大量新员工入职,需要批量创建 Crowd 用户.设置密码.分配应用组等机械性重复工作(主要还是懒~),故把这个加餐任务分配给刚来的测试同学去研究. 一是:让他了解下 Postman 的数 ...

随机推荐

  1. 安装Tesseract

    下载网站 https://digi.bib.uni-mannheim.de/tesseract/

  2. 第六篇:python中numpy.zeros(np.zeros)的使用方法

    用法:zeros(shape, dtype=float, order='C') 返回:返回来一个给定形状和类型的用0填充的数组: 参数:shape:形状 dtype:数据类型,可选参数,默认numpy ...

  3. jQuery编码中的一些技巧

    缓存变量 DOM遍历是昂贵的,所以尽量将会重用的元素缓存. // 糟糕 h = $('#element').height(); $('#element').css('height',h-20); // ...

  4. while循环中continue和break的区别

    除了满足while条件外,还有两种方法可以终止循环,它们分别是break和continue.它们唯一的区别是break跳出整个循环,直接执行下面的代码了;而continue是终止当次循环,不执行下面的 ...

  5. 用NPOI完成公司任务(主要就是导入导出操作)

    注意要先添加程序集的引用 导出到excel: public override IWorkbook writeExecl(string filePath, DataTable dt) { if (Fil ...

  6. oracle 11g 版本自带移除,省时省力

    ---oracle删除 app\Administrator\product\11.2.0\dbhome_1\deinstall.bat 指定要取消配置的所有单实例监听程序 [LISTENER]: En ...

  7. day21&22&23:线程、进程、协程

    1.程序工作原理 进程的限制:每一个时刻只能有一个线程来工作.多进程的优点:同时利用多个cpu,能够同时进行多个操作.缺点:对内存消耗比较高当进程数多于cpu数量的时候会导致不能被调用,进程不是越多越 ...

  8. 【Trapping Rain Water】cpp

    题目: Given n non-negative integers representing an elevation map where the width of each bar is 1, co ...

  9. PHP FILTER_VALIDATE_IP 过滤器

    FILTER_VALIDATE_IP 过滤器把值作为 IP 进行验证,用于验证 IP 是否合法,支持 IPV6 验证 例子 <?php $ip = "192.168.0.1" ...

  10. [python][django学习篇][10]再次修改博客首页模板

    目前我们看到的只是模板中预先填充的一些数据,我们得让它显示从数据库中获取的文章数据.下面来稍微改造一下模板: 删除所有article标签,然后添加以下内容,将从数据库读取到的内容填充到模板变量{{ p ...