由於項目中加入了新的功能,可以使管理員向數據庫中導入Excel數據。因此,在商品管理這塊需要對Excel進行操作,在網上查了些資料,根據項目的實際情況進行了壹定的優化,這裏簡單的介紹下。
1.C#代碼。
<span?style="font-family:Microsoft?YaHei;font-size:18px;">///?<summary>?
///?上傳Excel文件,並將數據導入到數據庫?
///?</summary>?
///?<param?name="sender"></param>?
///?<param?name="e"></param>?
protected?void?lbtnSure_Click(object?sender,?EventArgs?e)?
{?
//?定義變量,並賦初值?
string?url?=?this.fileUpLoad.PostedFile.FileName;?
string?urlLocation?=?"";?
//?判斷傳輸地址是否為空?
if?(url?==?"")?
{?
//?提示“請選擇Excel文件”? Page.ClientScript.RegisterStartupScript(Page.GetType(),?"message",?"<script?defer>alert('請選擇97~2003版Excel文件!');</script>");? return;? }? //?判斷獲取的是否為地址,而非文件名? if?(url.IndexOf("\\")?>?-1)? {? //?獲取文件名? urlLocation?=?url.Substring(url.LastIndexOf("\\")?+?1);//獲取文件名? }? else? {? //?url為文件名時,直接獲取文件名? urlLocation?=?url;? }? //?判斷指定目錄下是否存在文件夾,如果不存在,則創建? if?(!Directory.Exists(Server.MapPath("~\\up")))? {?//?創建up文件夾?
Directory.CreateDirectory(Server.MapPath("~\\up"));?
}? //在系統中建文件夾up,並將excel文件另存? this.fileUpLoad.SaveAs(Server.MapPath("~\\up")?+?"\\"?+?urlLocation);//記錄文件名到服務器相對應的文件夾中? //?Response.Write(urlLocation);? //?取得保存到服務器端的文件路徑? string?strpath?=?Server.MapPath("~\\up")?+?"\\"?+?urlLocation;? //?取得config中的字段? string?connectionString?=?ConfigurationManager.AppSettings["Connect"].ToString();? string?strCon?=?ConfigurationManager.AppSettings["strUpLoad"].ToString();? //?替換變量? strCon?=?strCon.Replace("$Con$",?strpath);? //?初始化導入Excel對象? ImportExcel?excel?=?new?ImportExcel();? //?調用方法,將Excel文件導入數據庫? excel.TransferData(strCon,?"t_Goods",?connectionString);?}</span> ?
2.TransferData類。
<span?style="font-family:Microsoft?YaHei;font-size:18px;">public?void?TransferData(string?strCon,?string?sheetName,?string?connectionString)?
{?
DataSet?ds?=?new?DataSet();?
try
{?
//獲取全部數據?
OleDbConnection?conn?=?new?OleDbConnection(strCon);?
conn.Open();?
string?strExcel?=?"";?
OleDbDataAdapter?myCommand?=?null;?
strExcel?=?string.Format("select?*?from?[{0}$]",?sheetName);?
myCommand?=?new?OleDbDataAdapter(strExcel,?strConn);?
myCommand.Fill(ds,?sheetName);?
//如果目標表不存在則創建,excel文件的第壹行為列標題,從第二行開始全部都是數據記錄
string?strSql?=?string.Format("if?not?exists(select?*?from?sysobjects?where?name?=?'{0}')?create?table?{0}(",?sheetName);//以sheetName為表名
foreach?(System.Data.DataColumn?c?in?ds.Tables[0].Columns)?
{?
strSql?+=?string.Format("[{0}]?varchar(255),",?c.ColumnName);?
}?
strSql?=?strSql.Trim(',')?+?")";?
using?(System.Data.SqlClient.SqlConnection?sqlconn?=?new?System.Data.SqlClient.SqlConnection(connectionString))?
{?
sqlconn.Open();?
System.Data.SqlClient.SqlCommand?command?=?sqlconn.CreateCommand();?
command.CommandText?=?strSql;?
command.ExecuteNonQuery();?
sqlconn.Close();?
}?
//用bcp導入數據?
//excel文件中列的順序必須和數據表的列順序壹致,因為數據導入時,是從excel文件的第二行數據開始,不管數據表的結構是什麽樣的,反正就是第壹列的數據會插入到數據表的第壹列字段中,第二列的數據插入到數據表的第二列字段中,以此類推,它本身不會去判斷要插入的數據是對應數據表中哪壹個字段的
using?(System.Data.SqlClient.SqlBulkCopy?bcp?=?new?System.Data.SqlClient.SqlBulkCopy(connectionString))?
{?
bcp.SqlRowsCopied?+=?new?System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);?
bcp.BatchSize?=?100;//每次傳輸的行數?
bcp.NotifyAfter?=?100;//進度提示的行數?
bcp.DestinationTableName?=?sheetName;//目標表?
bcp.WriteToServer(ds.Tables[0]);?
}?
}?
catch?(Exception?ex)?
{?
throw?new?Exception(ex);?
}
}?
//進度顯示?
void?bcp_SqlRowsCopied(object?sender,?System.Data.SqlClient.SqlRowsCopiedEventArgs?e)?
{?
}
}</span> ?
4.Web界面樣式。