C#实现excel导入到sql server 2008(.net版)

时间:2020-12-14 00:57:27
本来想把导入数据库后的数据通过gridview控件全部显示到界面,因为一旦进入页面所有控件的已经初始化好了,所以必须使用刷新数据源或用代码实现不用控件来绑定数据源,某位实现了这个功能可以发表下自己的意见
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using System.Collections;using System.Windows.Forms;using System.Data.OleDb;using System.Data.Common;using System.Data.SqlClient;public partial class Excel导入_Default : System.Web.UI.Page{    private static string filename;    private static string savePath;    private static DataSet ds; //要插入的数据    private static DataTable dt;    protected void Page_Load(object sender, EventArgs e)    {    }    //上传文件到指定的服务器    protected void Button1_Click1(object sender, EventArgs e)    {        filename = this.fileUploadExcel.FileName;        //savePath必须包含表名在内的所有路径名        savePath = @"G:\项目组文件\项目.net学习资料\工程\Health\Excel导入\Files\" + this.fileUploadExcel.FileName;    //上传服务器文件的存储,存在当前新建的文件夹        this.fileUploadExcel.SaveAs(savePath);        Boolean judge_excel = Judge_Excel();        if (!judge_excel)        {            MessageBox.Show("上传的不是excel文件", "标题", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);            return;        }        else            MessageBox.Show("上传文件成功", "标题", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);        //测试,将excel中的sheet1导入到sqlserver中           //string connString = "server=localhost;uid=sa;pwd=sqlgis;database=master";        //System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();        //if (fd.ShowDialog() == DialogResult.OK)        //{        //    //TransferData(fd.FileName, "sheet1", connString);        //}    }    //判断文件是否是excel文件函数    protected Boolean Judge_Excel()    {        string fileExtend = System.IO.Path.GetExtension(this.fileUploadExcel.FileName);        if (fileExtend == ".xlsx" || fileExtend == ".xls")            return true;        else            return false;    }    //获取excel数据按钮的触发,    protected void Button2_Click(object sender, EventArgs e)    {        ExcelToDataSet();        MessageBox.Show("获取数据成功", "标题", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);    }    //从excel表中获取数据的函数    public void ExcelToDataSet()    {        string strConn = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + savePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";        OleDbConnection conn = new OleDbConnection(strConn); //连接excel                    if (conn.State.ToString() == "Open")        {            conn.Close();        }        conn.Open();    //外部表不是预期格式,不兼容2010的excel表结构        string s = conn.State.ToString();        OleDbDataAdapter myCommand = null;        ds = null;        /*DataTable yTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });//获取表的框架,几行几列        string tableName = yTable.Rows[0]["filename"].ToString(); //表示的是几行几列          string strSel = "select * from [" + filename + "]";//xls */        string strExcel = "select * from [sheet1$]";  //如果有多个sheet表时可以选择是第几张sheet表            myCommand = new OleDbDataAdapter(strExcel, conn);//用strExcel初始化myCommand,查看myCommand里面的表的数据??        ds = new DataSet();        myCommand.Fill(ds);     //把表中的数据存放在ds(dataSet)        conn.Close();        try        {            dt = ds.Tables[0];            this.dataGridView1.DataSource = dt;        }        catch (Exception err)        {            MessageBox.Show("操作失败!" + err.ToString());        }    }    //excel导入数据库sql的按钮触发    protected void Button3_Click(object sender, EventArgs e)    {        //string path = @"D:\数据库SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Test.mdf";        string connString = "server=localhost;uid=sa;pwd=1234;database=Test";   //连接数据库的路径方法        //String connString=@"server=localhost;uid=sa;pwd=1234;database=D:\数据库SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Test.mdf";        SqlConnection conn = new SqlConnection(connString);        conn.Open();        DataRow dr = null;        int C_Count = dt.Columns.Count;//获取列数        for (int i = 0; i < dt.Rows.Count; i++)  //记录表中的行数,循环插入        {            dr = dt.Rows[i];            insertToSql(dr, C_Count, conn);        }        conn.Close();               if (dataGridView1.Rows.Count > 0)  //把数据库表中的数据显示到表中,可判断有没有数据        {            MessageBox.Show("导入成功!");        }        else        {            MessageBox.Show("没有数据!");        }    }    //使用bcp,不容易出错而且效率高    /*try    {        using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connString))        {            bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);            bcp.BatchSize = 100;//每次传输的行数               bcp.NotifyAfter = 100;//进度提示的行数               bcp.DestinationTableName = savePath;//目标表               bcp.WriteToServer(ds.Tables[0]);        }       }    catch    {        System.Windows.Forms.MessageBox.Show(ex.Message);    }*/    //插入数据库的函数    protected void insertToSql(DataRow dr, int column_count, SqlConnection conn)    {        //excel表中的列名和数据库中的列名一定要对应          string name = dr[0].ToString();//需要把内个列都列出来        string age = dr[1].ToString();        string sex = dr[2].ToString();        //当数据库中有多个表时,怎么分辨插入的表        string sql = "insert into 客户 values('" + name + "','" + age + "','" + sex + "')";        SqlCommand cmd = new SqlCommand(sql, conn);        cmd.ExecuteNonQuery();    }    //从excel表中获取数据并存在    //    protected void ImportFromExcel()    //    {    //        string execelConnectionStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=filename;    //        Extended Properties=""Excel 8.0;HDR=YES;IMEX=1\""";//表第一行是标题,不做为数据使用, Excel 档案只能用来做“读取”用途。    //        ds = new DataSet();    //        string connString = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "     //            + savePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";    //        DataTable table = OleDbHelper.GetExcelTables(connString);    //        if (table == null || table.Rows.Count <= 0)    //        {    //            return;    //        }    //        foreach (DataRow dr in table.Rows)    //        {    //            string cmdText = "select * from [" + dr["TABLE_NAME"].ToString() + "]";    //            DataTable dt = OleDbHelper.FillDataTable(connString, cmdText);    //            dt.TableName = dr["TABLE_NAME"].ToString();    //            ds.Tables.Add(dt);    //        }    //    }}