将数据从Excel文件导入数据库表 [英] Import Data from Excel File into Database table

查看:90
本文介绍了将数据从Excel文件导入数据库表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我最近一直在寻找能够上传excel文件并将数据导入数据库表的代码我发现似乎没有工作。



谢谢,

Leroy

Hi everyone,

I have been looking around recently for some codes that would allow me to upload an excel file and import the data into a database table but those that I have found dont seem to work.

Thanks,
Leroy

推荐答案

尝试下面的代码按钮导入点击



Try this below code on button import click

protected void btnImport_Click(object sender, EventArgs e)
        {         
            if (!FileUpload1.HasFile)
            {
                try
                {
                    string path = string.Concat(Server.MapPath("~/Uploaded Folder/" + FileUpload1.FileName)); 
                    FileUpload1.SaveAs(path);
 
                    // Connection String to Excel Workbook
                    string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);
                    OleDbConnection connection = new OleDbConnection();
                    connection.ConnectionString = excelConnectionString;
                    OleDbCommand command = new OleDbCommand("select * from [Sheet1


,连接);
connection.Open();
// 创建DbDataReader到数据工作表
DbDataReader dr = command.ExecuteReader( );

// SQL Server连接字符串
string sqlConnectionString = @ 数据源= MYPC;初始目录=学生;用户ID = SA;密码= Wintellect的;

// 批量复制到SQL Server
SqlBulkCopy bulkInsert = new SqlBulkCopy(sqlConnectionString);
bulkInsert.DestinationTableName = Student_Record;
bulkInsert.WriteToServer(dr);
Label1.Text = Ho Gaya;
}

Catch(例外情况)
{
label.text = ex.Message.ToString();
}
}
", connection); connection.Open(); // Create DbDataReader to Data Worksheet DbDataReader dr = command.ExecuteReader(); // SQL Server Connection String string sqlConnectionString = @"Data Source=MYPC;Initial Catalog=Student;User ID=sa;Password=wintellect"; // Bulk Copy to SQL Server SqlBulkCopy bulkInsert = new SqlBulkCopy(sqlConnectionString); bulkInsert.DestinationTableName = "Student_Record"; bulkInsert.WriteToServer(dr); Label1.Text = "Ho Gaya"; } Catch(Exception ex) { label.text=ex.Message.ToString(); } }


这篇关于将数据从Excel文件导入数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆