基于NET的Excel导入MSSQL2008

开发机器:(需安装AccessDatabaseEngine2007x32,不兼容64bit的oledb,出现未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序

操作系统:Window8企业版64bit

数据库:   MSSQL2008R2_64Bit

MS-Office: Office2010_64Bit, 

服务器:

操作系统WindowServer2003R2(32位)

数据库:   MSSQL2008(32位)

MS-Office:  Office2007(32位)


注:Access2007或2010都是提供Microsoft.ACE.OLEDB.12.0 。如果Excel2010请将“Excel 14.0”添加到 OLEDB 连接字符串的扩展属性中。 


AccessDatabaseEngine2010下载地址:http://www.microsoft.com/zh-cn/download/details.aspx?id=13255

AccessDatabaseEngine2007下载地址:http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exe


数据库表结构:

Eecel测试数据:




1.基于MSSQL2008数据库管理器--新建查询

--开启导入功能
exec sp_configure 'show advanced options',1
reconfigure
exec sp_configure 'Ad Hoc Distributed Queries',1
reconfigure
--允许在进程中使用ACE.OLEDB.12
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
--允许动态参数
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1

insert into Student select * from 
OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;HDR=YES;DATABASE=d:\test.xlsx',sheet1$)

exec sp_configure 'Ad Hoc Distributed Queries',0
reconfigure
exec sp_configure 'show advanced options',0
reconfigure 
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 0
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 0


(备注:不同版本Excel的OleDb连接串格式)
excel 2000 ~ 2003:
Provider=Microsoft.Jet.OleDb.4.0;Data Source='excel文件路径';Extended Properties='Excel 8.0;HDR=YES'
excel 2007 :
Provider=Microsoft.Ace.OleDb.12.0;Data Source='excel文件路径';Extended Properties='Excel 12.0;HDR=YES'

Excel2000-2003:
OleDbConnection ExcelConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + FilePath + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1'");
Excel2007:
OleDbConnection ExcelConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + FilePath + "; Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1'");

注:FilePath是excel文件的路径 导入Excel2007文件时机器上必须安装有Excel2007否则会报错.


结果





不够智能化,列头标题也当作一行数据录入数据表,还有最后列数据混乱


二:基于Net后台编码的导入:

     //前台简单一个上传控件和按钮  
    <form id="form1" runat="server">
    <div>    
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" οnclick="Button1_Click" Text="导入" />    
    </div>
    </form> 
 
        //后台按钮事件      
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile == false)
            {
                Response.Write("<script>alert('请您选择Excel文件')</script> ");
                return;//当无文件时,返回
            }
            int fileSize = 4;
            int fileLenth = FileUpload1.PostedFile.ContentLength / (1024 * 1024);
            //大小是否在限制内
            if (fileLenth > fileSize)
            {
                Response.Write("<script>alert('文件不能大于" + fileSize + "M')</script> ");
                return ;
            }
            string fileType  = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
            if (fileType == ".xls" || fileType == ".xlsx")
            {
                string fileDirectory = "Excel";
                string serverPath = Server.MapPath(fileDirectory);
                //是否存在目录,不存在先创建
                if (!System.IO.Directory.Exists(serverPath))
                {
                    System.IO.Directory.CreateDirectory(serverPath);
                }
                string newPath = serverPath + "\\" + FileUpload1.FileName;
                FileUpload1.SaveAs(newPath);
                
                DataTable dt = ExcelDataSource(newPath, "sheet1").Tables[0];
                ExcelToDB.BLL.Student_BLL bll = new Student_BLL();
                if (bll.Add2(dt))
                {
                    Response.Write("<script>alert('导入成功!')</script>");
                }
                else
                {
                    Response.Write("<script>alert('导入失败!')</script>");
                }
                
            }
            else
            {
                Response.Write("<script>alert('只可以选择Excel文件')</script>");
                return;//当选择的不是Excel文件时,返回
            }
               
        }

        /// <summary>
        /// 获取Excel数据源,填充到DataSet
        /// </summary>
        /// <param name="filepath">excel文件绝对路径</param>
        /// <param name="sheetname">excel表单名</param>
        /// <returns></returns>
        public DataSet ExcelDataSource(string filepath, string sheetname)
        {
            string strConn;
            strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";
            OleDbConnection conn = new OleDbConnection(strConn);
            OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetname + "$]", strConn);
            DataSet ds = new DataSet();
            oada.Fill(ds);
            return ds;
        }
结果:








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Excel 数据导入到 MySQL 数据库可以分为以下几个步骤: 1.读取 Excel 数据 可以使用 C# 中的 OLEDB 或者 EPPlus 库来读取 Excel 数据。其中 OLEDB 是基于 COM 的组件,可以读取 Excel 2003 以前的版本,而 EPPlus 是基于 Open XML 标准的库,可以读取 Excel 2007 及以后的版本。 2.连接 MySQL 数据库 使用 MySQL 数据库提供的 .NET Connector 组件来连接 MySQL 数据库。 3.创建表格 在 MySQL 数据库中创建表格,确保表格的字段与 Excel 数据的字段匹配。 4.插入数据 将读取到的 Excel 数据插入到 MySQL 数据库中对应的表格中。 以下是示例代码: ```csharp using System.Data; using System.Data.OleDb; using MySql.Data.MySqlClient; using OfficeOpenXml; public void ImportDataFromExcelToMySQL(string excelFilePath, string mysqlConnectionString) { // 读取 Excel 数据 DataTable excelData = ReadExcelData(excelFilePath); // 连接 MySQL 数据库 MySqlConnection mysqlConnection = new MySqlConnection(mysqlConnectionString); mysqlConnection.Open(); // 创建表格 CreateTable(mysqlConnection); // 插入数据 InsertData(mysqlConnection, excelData); // 关闭连接 mysqlConnection.Close(); } private DataTable ReadExcelData(string excelFilePath) { // 使用 OLEDB 读取 Excel 2003 以前的版本 string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'"; using (OleDbConnection excelConnection = new OleDbConnection(excelConnectionString)) { excelConnection.Open(); OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", excelConnection); DataTable excelData = new DataTable(); excelDataAdapter.Fill(excelData); return excelData; } // 使用 EPPlus 读取 Excel 2007 及以后的版本 // using (ExcelPackage excelPackage = new ExcelPackage(new FileInfo(excelFilePath))) // { // ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets["Sheet1"]; // DataTable excelData = worksheet.ConvertSheetToDataTable(); // return excelData; // } } private void CreateTable(MySqlConnection mysqlConnection) { MySqlCommand createTableCommand = new MySqlCommand("CREATE TABLE IF NOT EXISTS `table_name` (`column1` VARCHAR(50), `column2` VARCHAR(50), `column3` INT)", mysqlConnection); createTableCommand.ExecuteNonQuery(); } private void InsertData(MySqlConnection mysqlConnection, DataTable excelData) { foreach (DataRow row in excelData.Rows) { MySqlCommand insertCommand = new MySqlCommand("INSERT INTO `table_name` (`column1`, `column2`, `column3`) VALUES (@column1, @column2, @column3)", mysqlConnection); insertCommand.Parameters.AddWithValue("@column1", row["column1"].ToString()); insertCommand.Parameters.AddWithValue("@column2", row["column2"].ToString()); insertCommand.Parameters.AddWithValue("@column3", int.Parse(row["column3"].ToString())); insertCommand.ExecuteNonQuery(); } } ``` 其中,`excelFilePath` 为 Excel 文件的路径,`mysqlConnectionString` 为 MySQL 数据库的连接字符串。在 `ReadExcelData` 方法中,使用了 OLEDB 来读取 Excel 数据,读取的表格名为 `Sheet1`,如果需要读取其他的表格,可以修改查询语句。在 `CreateTable` 方法中,创建了一个名为 `table_name` 的表格,其中包含三个字段,可以根据自己的需要修改字段名和类型。在 `InsertData` 方法中,使用了参数化查询来插入数据,确保数据的安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值