asp.net 操作Excel表数据导入到SQL Server数据库

时间:2022-01-08 06:38:28

代码全部贴出,主要是Excel表中的数据要和数据库中的数据类型要匹配。

这里Excel表中的字段是:

姓名性别班级学号初始密码

SQL Server表tb_Users中的字段是;

RealNameSexInClassQuestionAnswer


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="TEST_Default" %>

<!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" />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
    </div>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
using USTC;
using System.Drawing;

public partial class TEST_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //获取文件路径
        string filePath = this.FileUpload1.PostedFile.FileName;
        if (filePath != "")
        {
            if (filePath.Contains("xls"))//判断文件是否存在
            {
                InputExcel(filePath);
            }
            else
            {
                Response.Write("请检查您选择的文件是否为Excel文件!谢谢!");
            }
        }

        else
        {
            Response.Write("请先选择导入文件后,再执行导入!谢谢!");
        }
    }

    private void InputExcel(string pPath)
    {
         string conn = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + pPath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
        OleDbConnection oleCon = new OleDbConnection(conn);
        oleCon.Open();
        string Sql = "select * from [Sheet1$]";
        OleDbDataAdapter mycommand = new OleDbDataAdapter(Sql, oleCon);
        DataSet ds = new DataSet();
        mycommand.Fill(ds, "[Sheet1$]");
        oleCon.Close();
        int count = ds.Tables["[Sheet1$]"].Rows.Count;
        for (int i = 0; i < count; i++)
        {
            string tRealName, tSex, tInClass, tQuestion, tAnswer;
            tRealName = ds.Tables["[Sheet1$]"].Rows[i]["姓名"].ToString().Trim();
            tSex = ds.Tables["[Sheet1$]"].Rows[i]["性别"].ToString().Trim();
            tInClass = ds.Tables["[Sheet1$]"].Rows[i]["班级"].ToString().Trim();
            tQuestion = ds.Tables["[Sheet1$]"].Rows[i]["学号"].ToString().Trim();
            tAnswer = ds.Tables["[Sheet1$]"].Rows[i]["初始密码"].ToString().Trim();
            string excelsql = "insert into tb_Users(RealName, Sex, InClass,Question,Answer) values ('" + tRealName + "','" + tSex + "','" + tInClass + "','" + tQuestion + "','" + tAnswer + "')";
            try
            {
                //导入到SQL Server中
                DM dm = new DM();
                dm.execsql(excelsql);
                Response.Write("<script language='javascript'>Alert('数据导入成功!');window.location='Default.aspx'</script>");
            }
            catch(Exception)
            {
                Response.Write("<script language='javascript'>Alert('数据导入失败!');window.location='Default.aspx'</script>");
            }
        }
    }
}