using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Collections;
using System.Data.OleDb;
using System.Data.SqlClient;namespace ExcelToSql
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        // 选择Excel文件
        private void btnChooseExcel_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog odlgExcel = new OpenFileDialog())
            {
                odlgExcel.Multiselect = false;
                if (odlgExcel.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        ExcelFileName.Text = odlgExcel.FileName;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }        // 将Excel中的数据导入到SQL数据库中
        private void btnImport_Click(object sender, EventArgs e)
        {
            DataSet ds = ImportSql(ExcelFileName.Text.Trim());
            DataTable dt = ds.Tables[0];            try
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string strInsertComm = string.Format("insert into T_Region (RegionShortName,RegionFullName,DisplayOrder) values ({0},{1},{2})",
                                                        dr["区域简称"].ToString(),
                                                        dr["区域全称"].ToString(),
                                                        dr["序号"].ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }        public static System.Data.DataSet FillDataSet(string FilePath)
        {
            ArrayList TableList = new ArrayList();
            TableList = GetExcelTables(FilePath);
            if (TableList.Count <= 0)
            {
                return null;
            }            DataTable table;
            DataSet ds = new DataSet();
            OleDbConnection oledbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";Extended Properties=Excel 8.0");
            try
            {
                if (oledbcon.State == ConnectionState.Closed)
                {
                    oledbcon.Open();
                }
                for (int i = 0; i < TableList.Count; i++)
                {
                    string dtname = TableList[i].ToString();
                    try
                    {
                        OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", oledbcon);
                        OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
                        table = new DataTable(dtname);
                        adapter.Fill(table);
                        ds.Tables.Add(table);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            finally
            {
                if (oledbcon.State == ConnectionState.Open)
                {
                    oledbcon.Close();
                }
            }
            return ds;
        }        // Excel导入数据库
        public static DataSet ImportSql(string FilePath)
        {
            return FillDataSet(FilePath);
        }        public static ArrayList GetExcelTables(string FilePath)
        {
            DataTable dt = new DataTable();
            ArrayList al = new ArrayList();            if (File.Exists(FilePath))
            {
                string strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";Extended Properties=Excel 8.0";
                using (OleDbConnection conn = new OleDbConnection(strcon))
                {
                    try
                    {
                        conn.Open();
                        dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            return al;
        }        
    }
}
DataTable dt = ds.Tables[0];这里错误!外部表不是预期格式!
请教高手!或给个winform的excel导入sql server完整代码!!谢谢

解决方案 »

  1.   

    求完整代码可以搜索以前的帖子,这个问题被人问了无数次了。
    思路都是一样的,先读进内存然后在sql进去
    Good luck
      

  2.   

    不是这句话错了,是你的取数据时出错了。查看一下你的取excel代码。跟踪一下,就知道到底哪里错了。不要局限在这行上。是里面错了。
      

  3.   

    look this:
    http://www.codeproject.com/KB/database/ImportExcelToSQLVB_Net.aspx
      

  4.   


    Excel导入SQL数据库完整代码2007-06-12 16:03Excel导入SQL数据库完整代码 
    protected void studentload_Click(object sender, EventArgs e)
         {//批量添加学生信息
             SqlConnection conn = DB.dataBaseConn();//链接数据库
             conn.Open();
              try
              {
                 string fileurl = typename(studentFileUpload);//调用typename方法取得excel文件路径
                 DataSet ds = new DataSet();//取得数据集
                 ds = xsldata(fileurl);
                 int errorcount = 0;//记录错误信息条数
                 int insertcount = 0;//记录插入成功条数
                 int updatecount = 0;//记录更新信息条数
                  for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                 {
                     string stuid = ds.Tables[0].Rows[i][0].ToString();
                     string stuname = ds.Tables[0].Rows[i][1].ToString();
                     string stusex = ds.Tables[0].Rows[i][2].ToString();
                     string zhuanye = ds.Tables[0].Rows[i][3].ToString();
                     string classname = ds.Tables[0].Rows[i][4].ToString();
                     if (stuid != "" && stuname != "" && stusex != "" && zhuanye != "" && classname != "")
                     {
                                       SqlCommand selectcmd = new SqlCommand("select count(*) from zy_class   where zhuanye='" + zhuanye + "'and classname='" + classname + "'", conn);
                         int count = Convert.ToInt32(selectcmd.ExecuteScalar());
                         if (count > 0)
                         {
                             SqlCommand selectcmd2 = new SqlCommand("select count(*) from stud where   stuid='" + stuid + "'", conn);
                             int count2 = Convert.ToInt32(selectcmd2.ExecuteScalar());
                             if (count2 > 0)
                             {
                                 SqlCommand updatecmd = new SqlCommand("update stud set   stuname='" + stuname + "',stusex='" + stusex + "',zhuanye='" + zhuanyei + "',classname='" + classname + "'   where stuid='" + stuid + "'", conn);
                                 updatecmd.ExecuteNonQuery();
                                 updatecount++;
                             }
                             else
                             {
                                 SqlCommand insertcmd= new SqlCommand("insert into stud    values('" + stuid + "','" + stuname + "','" + stusex + "','" + zhuanye + "','" + classname+ "')", conn);
                                 insertcmd.ExecuteNonQuery();
                                 insertcount++;
                             }
                         }
                         else
                         {
                             Response.Write("<script language='javascript'>alert('专业或班级信息有错!导入失败!请检查!');</script>");
                             break;                        }
                     }
                     else
                     {
                         errorcount++;
                     }
                 }
                 Response.Write("<script language='javascript'>alert('" + insertcount + "条数据导入成功!" + updatecount + "条数据更新成功!" + errorcount + "条数据部分信息为空没有导入!');</script>");
             }
             catch (Exception e)
             {
                 Response.Write("<script language='javascript'>alert('导入失败!');</script>");
             }
             finally
             {
                 conn.Close();
             }    
         }//把EXCEL文件上传到服务器并返回文件路径private String typename(FileUpload fileloads)
         {
             string fullfilename = fileloads.PostedFile.FileName;
             string filename = fullfilename.Substring(fullfilename.LastIndexOf("\\") + 1);
             string type = fullfilename.Substring(fullfilename.LastIndexOf(".") + 1);
             string murl = "";
             if (type == "xls")
             {
                 fileloads.PostedFile.SaveAs(Server.MapPath("excel") + "\\" + filename);
                 murl = (Server.MapPath("excel") + "\\" + filename).ToString();
             }
             else
             {
                 Response.Write("<script language='javascript'>alert('导入文件格式不对!');</script>");         }
             return murl;
         }   //把excel数据读入dataset返回l数据集private DataSet xsldata(string filepath)
         {
             string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;IMEX=1'";
             System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strCon);
             string strCom = "SELECT * FROM [Sheet1$]";
             Conn.Open();
             System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn);
             DataSet ds = new DataSet();
             myCommand.Fill(ds, "[Sheet1$]");
             Conn.Close();
             return ds;
         } 
      

  5.   


    protected void studentload_Click(object sender, EventArgs e)
         {//批量添加学生信息
             SqlConnection conn = DB.dataBaseConn();//链接数据库
             conn.Open();
              try
              {
                 string fileurl = typename(studentFileUpload);//调用typename方法取得excel文件路径
                 DataSet ds = new DataSet();//取得数据集
                 ds = xsldata(fileurl);
                 int errorcount = 0;//记录错误信息条数
                 int insertcount = 0;//记录插入成功条数
                 int updatecount = 0;//记录更新信息条数
                  for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                 {
                     string stuid = ds.Tables[0].Rows[i][0].ToString();
                     string stuname = ds.Tables[0].Rows[i][1].ToString();
                     string stusex = ds.Tables[0].Rows[i][2].ToString();
                     string zhuanye = ds.Tables[0].Rows[i][3].ToString();
                     string classname = ds.Tables[0].Rows[i][4].ToString();
                     if (stuid != "" && stuname != "" && stusex != "" && zhuanye != "" && classname != "")
                     {
                                       SqlCommand selectcmd = new SqlCommand("select count(*) from zy_class   where zhuanye='" + zhuanye + "'and classname='" + classname + "'", conn);
                         int count = Convert.ToInt32(selectcmd.ExecuteScalar());
                         if (count > 0)
                         {
                             SqlCommand selectcmd2 = new SqlCommand("select count(*) from stud where   stuid='" + stuid + "'", conn);
                             int count2 = Convert.ToInt32(selectcmd2.ExecuteScalar());
                             if (count2 > 0)
                             {
                                 SqlCommand updatecmd = new SqlCommand("update stud set   stuname='" + stuname + "',stusex='" + stusex + "',zhuanye='" + zhuanyei + "',classname='" + classname + "'   where stuid='" + stuid + "'", conn);
                                 updatecmd.ExecuteNonQuery();
                                 updatecount++;
                             }
                             else
                             {
                                 SqlCommand insertcmd= new SqlCommand("insert into stud    values('" + stuid + "','" + stuname + "','" + stusex + "','" + zhuanye + "','" + classname+ "')", conn);
                                 insertcmd.ExecuteNonQuery();
                                 insertcount++;
                             }
                         }
                         else
                         {
                             Response.Write("<script language='javascript'>alert('专业或班级信息有错!导入失败!请检查!');</script>");
                             break;                        }
                     }
                     else
                     {
                         errorcount++;
                     }
                 }
                 Response.Write("<script language='javascript'>alert('" + insertcount + "条数据导入成功!" + updatecount + "条数据更新成功!" + errorcount + "条数据部分信息为空没有导入!');</script>");
             }
             catch (Exception e)
             {
                 Response.Write("<script language='javascript'>alert('导入失败!');</script>");
             }
             finally
             {
                 conn.Close();
             }    
         }//把EXCEL文件上传到服务器并返回文件路径private String typename(FileUpload fileloads)
         {
             string fullfilename = fileloads.PostedFile.FileName;
             string filename = fullfilename.Substring(fullfilename.LastIndexOf("\\") + 1);
             string type = fullfilename.Substring(fullfilename.LastIndexOf(".") + 1);
             string murl = "";
             if (type == "xls")
             {
                 fileloads.PostedFile.SaveAs(Server.MapPath("excel") + "\\" + filename);
                 murl = (Server.MapPath("excel") + "\\" + filename).ToString();
             }
             else
             {
                 Response.Write("<script language='javascript'>alert('导入文件格式不对!');</script>");         }
             return murl;
         }   //把excel数据读入dataset返回l数据集private DataSet xsldata(string filepath)
         {
             string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;IMEX=1'";
             System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strCon);
             string strCom = "SELECT * FROM [Sheet1$]";
             Conn.Open();
             System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn);
             DataSet ds = new DataSet();
             myCommand.Fill(ds, "[Sheet1$]");
             Conn.Close();
             return ds;
         }