导入Excel文件批量导入ToSQLServer数据库
2009-11-27 10:12
465 查看
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.Web.Configuration;
using System.IO;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
/// <summary>
/// 得到Excel表数据
/// </summary>
/// <returns>Excel表数据</returns>
private DataSet GetExcelFileData()
{
//存放Excel文件数据
DataSet dsExcel = new DataSet();
try
{
//得到选择的Excel文件
string readerExcelFile = excelFilePath.Value;
//保存服务器Excel文件路径
string serverExcelFile = readerExcelFile.Substring(readerExcelFile.LastIndexOf('//')+1,readerExcelFile.Length - readerExcelFile.LastIndexOf('//')-1);
//服务器导入的Excel文件
string serverImportExcelFilePath = @"~/ImportExcelFile/" + serverExcelFile;
//映射到服务器本地的物理路径
string physicalExcelPath = Server.MapPath(serverImportExcelFilePath);
//获取文件名的后缀名
string fileExt = System.IO.Path.GetExtension(readerExcelFile);
//判断Excel文件扩展名(2003-2007)
if (fileExt == ".xls" || fileExt == ".xlsx")
{
if (File.Exists(physicalExcelPath))
{
File.Delete(physicalExcelPath);
}
//导入Excel文件保存到服务器
excelFilePath.PostedFile.SaveAs(physicalExcelPath);
//获取Excel2007文件驱动
string excelDriveConnection = WebConfigurationManager.AppSettings["ExcelDrive"];
if (!string.IsNullOrEmpty(excelDriveConnection))
{
excelDriveConnection = string.Format(excelDriveConnection, physicalExcelPath);
OleDbConnection excelConnection = new OleDbConnection(excelDriveConnection);
excelConnection.Open();
DataTable schemaTable = excelConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
int sheetCount = schemaTable.Rows.Count;
for (int i = 0; i < sheetCount; i++)
{
string tableName = schemaTable.Rows[i][2].ToString().Trim();
DataTable dt = new DataTable(tableName.Replace("$", ""));
string strSql = "Select * From [" + tableName + "]";
OleDbCommand objCmd = new OleDbCommand(strSql, excelConnection);
OleDbDataAdapter sqlada = new OleDbDataAdapter();
sqlada.SelectCommand = objCmd;
sqlada.Fill(dt);
dsExcel.Tables.Add(dt);
}
excelConnection.Close();
}
}
}
catch
{
//Response.Write("<script language='javascript'>alert('" + ex.Message + "');</script>"
}
return dsExcel;
}
/// <summary>
/// Excel文件数据保存到数据库
/// </summary>
/// <param name="dsExcel"> Excel文件数据</param>
/// <returns>处理结果</returns>
private bool ExcelDataToDataTable(DataSet dsExcel)
{
DataSet ds = new DataSet();
//------------------------------------------------------------------------------------
//获取批量插入的表
string dbConnectionStr = WebConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(dbConnectionStr);
string selectStr = " SELECT id,name,remark from test_2009 ";
SqlCommand cmd = new SqlCommand(selectStr, conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
conn.Open();
sda.Fill(ds);
conn.Close();
//------------------------------------------------------------------------------------
//删除所有测试数据
string deleteStr = " delete from test_2009";
cmd = new SqlCommand(deleteStr, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
//------------------------------------------------------------------------------------
//得到插入的数据
foreach (DataRow dExcelRow in dsExcel.Tables[0].Rows)
{
DataRow newRow = ds.Tables[0].NewRow();
newRow["id"] = dExcelRow["序号"].ToString();
newRow["name"] = dExcelRow["名称"].ToString();
newRow["remark"] = dExcelRow["备注"].ToString();
ds.Tables[0].Rows.Add(newRow);
}
//-------------------------------------------------------------------------------------
//在批量添加数据前的准备工作
string sql = "insert into test_2009(id,name,remark) VALUES (@id,@name,@remark)";
sda.InsertCommand = new SqlCommand(sql, conn);
SqlParameter param = new SqlParameter();
param = sda.InsertCommand.Parameters.Add(new SqlParameter("@id", SqlDbType.Int, 4));
param.SourceVersion = DataRowVersion.Current;
param.SourceColumn = "id";
param = sda.InsertCommand.Parameters.Add(new SqlParameter("@name", SqlDbType.VarChar, 50));
param.SourceVersion = DataRowVersion.Current;
param.SourceColumn = "name";
param = sda.InsertCommand.Parameters.Add(new SqlParameter("@remark", SqlDbType.VarChar, 50));
param.SourceVersion = DataRowVersion.Current;
param.SourceColumn = "remark";
//-------------------------------------------------------------------------------------
bool isResult = false;
conn.Open();
//批量插入
if (sda.Update(ds) > 0)
{
isResult = true;
}
conn.Close();
return isResult;
}
/// <summary>
/// 导入Excel文件
/// </summary>
/// <param name="sender">固定参数</param>
/// <param name="e">固定参数</param>
protected void btnImportExcel_Click(object sender, EventArgs e)
{
//获取Excel文件数据
DataSet dsExcel = GetExcelFileData();
//获取处理结果
bool isResult = ExcelDataToDataTable(dsExcel);
if (isResult)
{
Response.Write("<script language='javascript'>alert('导入成功');</script>");
}
}
}
webConfig文件配置
<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
/Windows/Microsoft.Net/Framework/v2.x/Config
-->
<configuration>
<appSettings>
//配置的是Excel文件2007驱动
<add key="ExcelDrive" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES'"/>
//配置的是Excel文件2003驱动
<add key="Excel2003Drive" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"/>
</appSettings>
<connectionStrings>
<add name="dbConnection" providerName="System.Data.SqlClient" connectionString="server=172.16.0.23;database=student;uid=sa;pwd=edufe" />
</connectionStrings>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true"/>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<customErrors mode="Off"></customErrors>
</system.web>
</configuration>
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.Web.Configuration;
using System.IO;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
/// <summary>
/// 得到Excel表数据
/// </summary>
/// <returns>Excel表数据</returns>
private DataSet GetExcelFileData()
{
//存放Excel文件数据
DataSet dsExcel = new DataSet();
try
{
//得到选择的Excel文件
string readerExcelFile = excelFilePath.Value;
//保存服务器Excel文件路径
string serverExcelFile = readerExcelFile.Substring(readerExcelFile.LastIndexOf('//')+1,readerExcelFile.Length - readerExcelFile.LastIndexOf('//')-1);
//服务器导入的Excel文件
string serverImportExcelFilePath = @"~/ImportExcelFile/" + serverExcelFile;
//映射到服务器本地的物理路径
string physicalExcelPath = Server.MapPath(serverImportExcelFilePath);
//获取文件名的后缀名
string fileExt = System.IO.Path.GetExtension(readerExcelFile);
//判断Excel文件扩展名(2003-2007)
if (fileExt == ".xls" || fileExt == ".xlsx")
{
if (File.Exists(physicalExcelPath))
{
File.Delete(physicalExcelPath);
}
//导入Excel文件保存到服务器
excelFilePath.PostedFile.SaveAs(physicalExcelPath);
//获取Excel2007文件驱动
string excelDriveConnection = WebConfigurationManager.AppSettings["ExcelDrive"];
if (!string.IsNullOrEmpty(excelDriveConnection))
{
excelDriveConnection = string.Format(excelDriveConnection, physicalExcelPath);
OleDbConnection excelConnection = new OleDbConnection(excelDriveConnection);
excelConnection.Open();
DataTable schemaTable = excelConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
int sheetCount = schemaTable.Rows.Count;
for (int i = 0; i < sheetCount; i++)
{
string tableName = schemaTable.Rows[i][2].ToString().Trim();
DataTable dt = new DataTable(tableName.Replace("$", ""));
string strSql = "Select * From [" + tableName + "]";
OleDbCommand objCmd = new OleDbCommand(strSql, excelConnection);
OleDbDataAdapter sqlada = new OleDbDataAdapter();
sqlada.SelectCommand = objCmd;
sqlada.Fill(dt);
dsExcel.Tables.Add(dt);
}
excelConnection.Close();
}
}
}
catch
{
//Response.Write("<script language='javascript'>alert('" + ex.Message + "');</script>"
}
return dsExcel;
}
/// <summary>
/// Excel文件数据保存到数据库
/// </summary>
/// <param name="dsExcel"> Excel文件数据</param>
/// <returns>处理结果</returns>
private bool ExcelDataToDataTable(DataSet dsExcel)
{
DataSet ds = new DataSet();
//------------------------------------------------------------------------------------
//获取批量插入的表
string dbConnectionStr = WebConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(dbConnectionStr);
string selectStr = " SELECT id,name,remark from test_2009 ";
SqlCommand cmd = new SqlCommand(selectStr, conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
conn.Open();
sda.Fill(ds);
conn.Close();
//------------------------------------------------------------------------------------
//删除所有测试数据
string deleteStr = " delete from test_2009";
cmd = new SqlCommand(deleteStr, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
//------------------------------------------------------------------------------------
//得到插入的数据
foreach (DataRow dExcelRow in dsExcel.Tables[0].Rows)
{
DataRow newRow = ds.Tables[0].NewRow();
newRow["id"] = dExcelRow["序号"].ToString();
newRow["name"] = dExcelRow["名称"].ToString();
newRow["remark"] = dExcelRow["备注"].ToString();
ds.Tables[0].Rows.Add(newRow);
}
//-------------------------------------------------------------------------------------
//在批量添加数据前的准备工作
string sql = "insert into test_2009(id,name,remark) VALUES (@id,@name,@remark)";
sda.InsertCommand = new SqlCommand(sql, conn);
SqlParameter param = new SqlParameter();
param = sda.InsertCommand.Parameters.Add(new SqlParameter("@id", SqlDbType.Int, 4));
param.SourceVersion = DataRowVersion.Current;
param.SourceColumn = "id";
param = sda.InsertCommand.Parameters.Add(new SqlParameter("@name", SqlDbType.VarChar, 50));
param.SourceVersion = DataRowVersion.Current;
param.SourceColumn = "name";
param = sda.InsertCommand.Parameters.Add(new SqlParameter("@remark", SqlDbType.VarChar, 50));
param.SourceVersion = DataRowVersion.Current;
param.SourceColumn = "remark";
//-------------------------------------------------------------------------------------
bool isResult = false;
conn.Open();
//批量插入
if (sda.Update(ds) > 0)
{
isResult = true;
}
conn.Close();
return isResult;
}
/// <summary>
/// 导入Excel文件
/// </summary>
/// <param name="sender">固定参数</param>
/// <param name="e">固定参数</param>
protected void btnImportExcel_Click(object sender, EventArgs e)
{
//获取Excel文件数据
DataSet dsExcel = GetExcelFileData();
//获取处理结果
bool isResult = ExcelDataToDataTable(dsExcel);
if (isResult)
{
Response.Write("<script language='javascript'>alert('导入成功');</script>");
}
}
}
webConfig文件配置
<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
/Windows/Microsoft.Net/Framework/v2.x/Config
-->
<configuration>
<appSettings>
//配置的是Excel文件2007驱动
<add key="ExcelDrive" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES'"/>
//配置的是Excel文件2003驱动
<add key="Excel2003Drive" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"/>
</appSettings>
<connectionStrings>
<add name="dbConnection" providerName="System.Data.SqlClient" connectionString="server=172.16.0.23;database=student;uid=sa;pwd=edufe" />
</connectionStrings>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true"/>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<customErrors mode="Off"></customErrors>
</system.web>
</configuration>
相关文章推荐
- excel文件(xls)批量导入sqlserver数据库
- 基于Spring3 MVC实现基于form表单上传Excel文件,批量导入数据时,报错:Unable to recognize OLE stream !
- 将指定文件夹下结构相同的EXCEL文件(支持2003和2007版本)批量导入到SQL数据库中指定的表
- 将指定文件夹下结构相同的EXCEL文件(支持2003和2007版本)批量导入到SQL数据库中指定的表
- 将指定文件夹下结构相同的EXCEL文件(支持2003和2007版本)批量导入到SQL数据库中指定的表
- 在access中批量导入excel文件
- SSIS将excel文件批量导入到sql server 2005
- SSIS(SQL Server2005 Integration Services)批量导入Excel文件 Excel连接报错解决
- Foxpro、excel文件批量导入数据到Mysql、Oracle
- 基于Spring MVC实现基于form表单上传Excel文件,批量导入数据
- 将指定文件夹下结构相同的EXCEL文件批量导入到SQL数据库中指定的表
- SSIS将excel文件批量导入到sql server 2005
- 将指定文件夹下结构相同的EXCEL文件(支持2003和2007版本)批量导入到SQL数据库中指定的表
- 修改导入本地EXCEL文件的函数(ALSM_EXCEL_TO_INTERNAL_TABLE)
- 从Excel文件读取数据批量导入到Mysql数据库
- 上传excel文件实现批量导入数据及导出数据为excel文件
- 如何批量从Excel文件中导入数据到数据库(一)
- 批量将制定文件夹下的全部Excel文件导入微软SQL数据库
- mysql与Oracle垃圾用户方案临时给的excel文件数据批量数据导入库操作步骤整理
- mvc4 强大的导出和不需要上传文件的批量导入EXCEL--SNF快速开发平台3.1