您的位置:首页 > 编程语言 > C#

c#大圣之路笔记——c#通过页面把excel中的数据导入到DB中(全部)

2016-05-03 13:35 543 查看
///html

<htmlxmlns="http://www.w3.org/1999/xhtml">
<headid="Head1"runat="server">
<title>批量修改</title>
<linkhref="../css/main.css"rel="stylesheet"type="text/css"/>
<linkhref="../css/Styles_1.css"rel="stylesheet"type="text/css"/>
<scripttype="text/javascript">

functionShowWaiting(){
document.getElementById('doing').style.visibility='visible';
}
functionCloseWaiting(){
document.getElementById('doing').style.visibility='hidden';
}
functionMyOnload(){
document.getElementById('doing').style.visibility='hidden';
}

if(window.onload==null){
window.onload=MyOnload;
}

</script>

</head>
<bodyms_positioning="GridLayout">
<formid="form1"runat="server"method="post">
<tablewidth="99%">
<tr>
<tdstyle="height:30px">
<b>批量修改</b>
</td>
</tr>
<trclass="SpliteLine"style="height:1px">
<tdstyle="background-color:#0071C5"></td>
</tr>
<tr>
<td>
<inputtype="file"id="myFile"name="myFile"runat="server"class="btnUpload"size="46"style="border:1pxsolid#ccc"/>
<asp:ButtonID="btnUpload"Text="上传数据"runat="server"CssClass="ButtonCommand"style="height:24px;width:60px;"OnClick="btnUpload_Click"/>
</td>
</tr>
<trclass="SpliteLine"style="height:1px">
<tdstyle="background-color:#0071C5"></td>
</tr>
<tralign="right">
<td>
<asp:ButtonID="btnExport"runat="server"Text="导出错误数据"CssClass="ButtonCommand"OnClick="btnExport_Click"style="height:24px;width:100px;"/>
</td>
</tr>
<tr>
<td>错误数据有:<asp:LabelID="errData"runat="server"></asp:Label>条。</td>
</tr>
<tr>
<td>
<asp:DataGridID="GridMain"runat="server"Width="99%"
AutoGenerateColumns="false"AllowPaging="true"PageSize="20"
AllowSorting="true"DataMember=""AlternatingItemStyle-BackColor="#EBE9E9"
OnPageIndexChanged="GridMain_PageIndexChanged"
onselectedindexchanged="GridMain_SelectedIndexChanged">
<AlternatingItemStyleCssClass="datagridAlternating"/>
<HeaderStyleCssClass="tableHead"Height="22"/>
<Columns>
<asp:BoundColumnDataField="errorMsg"HeaderText="错误原因">
<ItemStyleHorizontalAlign="Center"Width="25%"/>
</asp:BoundColumn>
<asp:BoundColumnDataField="stor_id"HeaderText="StoreID">
<ItemStyleHorizontalAlign="Center"Width="25%"/>
</asp:BoundColumn>
<asp:BoundColumnDataField="slsprs_id"HeaderText="SRID">
<ItemStyleHorizontalAlign="Center"Width="25%"/>
</asp:BoundColumn>
<asp:BoundColumnDataField="slsprs_nm"HeaderText="SRNM">
<ItemStyleHorizontalAlign="Center"Width="25%"/>
</asp:BoundColumn>
</Columns>
<PagerStylePosition="Top"Mode="NumericPages"/>
</asp:DataGrid>
</td>
</tr>
</table>
<div>

</div>
</form>
<divid='doing'style='z-index:12000;left:0px;width:100%;cursor:wait;position:absolute;top:0px;height:100%;filter:alpha(opacity=45);opacity:0.5;color:#000000;background-color:#FFFFFF;'>
<tablewidth='100%'height='100%'id="Table2">
<tralign='center'valign='middle'>
<td>
<tableid="Table3"class="loading">
<tralign='center'valign='middle'>
<td>
<imgsrc="../Images/Waitting.gif"/>
</td>
<td>  </td>
<tdvalign="middle">
<spanid=txtLoading0style="font-size:14px;color:#800080;font-weight:bold;">页面正在加载数据,请稍候...</span>
<br><spanid=txtLoading1style="font-size:14px;color:#800080;">Loading,pleasewait...</span>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>

</body>
</html>


///c#

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.IO;
usingCompIntelligenceWeb.User;

usingSystem.Data.OleDb;
usingSystem.Data;
usingSystem.Data.SqlClient;
usingSystem.Text;
usingMicrosoft.ApplicationBlocks.Data;

namespacePRCSales_external.Store
{
publicpartialclassXoemStoreSR_AsignUpdate:PageBase
{
protectedOleDbConnectionxlconn;
protectedOleDbDataAdapterxlda;
protectedDataTableErr_dt;
protectedstringtableName;
protectedstringWWID;

publicstringconnString=System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];

protectedvoidPage_Load(objectsender,EventArgse)
{
this.btnUpload.Attributes.Add("onclick","ShowWaiting();");
if(!IsPostBack)
{
WWID=((AccessControler)this.Session["_accessctrl"]).GetWWID();

initTable();
bindNextPage(0);
}
tableName=ViewState["TableName"].ToString();
Err_dt=(DataTable)ViewState["table"];

}

privatevoidbindNextPage(intp)
{
tableName=ViewState["TableName"].ToString();
Err_dt=(DataTable)ViewState["table"];
if(ViewState["Sort"].ToString()!="")
{
DataViewdv=newDataView(Err_dt);
dv.Sort=ViewState["Sort"].ToString();
GridMain.DataSource=dv;
}
else
{
GridMain.DataSource=Err_dt;
}
GridMain.CurrentPageIndex=p;
GridMain.DataBind();
}

protectedvoidGridMain_PageIndexChanged(objectsource,System.Web.UI.WebControls.DataGridPageChangedEventArgse)
{
currentPageIndex=e.NewPageIndex;
this.GridMain.CurrentPageIndex=currentPageIndex;
GridMain.DataSource=Err_dt;
GridMain.DataBind();
}

protectedintcurrentPageIndex
{
set
{
ViewState["currentPageIndex"]=value;
}
get
{
if(ViewState["currentPageIndex"]!=null)
{
returnint.Parse(ViewState["currentPageIndex"].ToString());
}
else
{
return0;
}
}
}

privatevoidinitTable()
{
tableName="XoemStoreSR_AsignUpdate"+DateTime.UtcNow.ToString();
Err_dt=newDataTable(tableName);
ViewState["TableName"]=tableName;
ViewState["table"]=Err_dt;
ViewState["Sort"]="";
}
///<summary>
///通过excel导入数据进入临时物理表
///</summary>
///<paramname="sender"></param>
///<paramname="e"></param>
protectedvoidbtnUpload_Click(objectsender,EventArgse)
{
if(this.myFile.PostedFile.FileName.Trim()=="")
{
stringmsg="请选择文件";
Response.Write("<scripttype='text/javascript'>alert('"+msg+"');</script>");
return;
}
//验证文件格式
stringext=this.myFile.PostedFile.FileName.Substring(this.myFile.PostedFile.FileName.LastIndexOf(".")).ToLower();
if(ext!=".xls"&&ext!=".xlsx")
{
stringmsg="文件格式错误!";
this.PageAlert(msg);
return;
}
if(!Directory.Exists(Server.MapPath("upload")))
{
Directory.CreateDirectory(Server.MapPath("upload"));
}
//文件路径
stringaFile=this.myFile.PostedFile.FileName.ToString();
//文件名
stringaFirstName=aFile.Substring(aFile.LastIndexOf("\\")+1,(aFile.LastIndexOf(".")-aFile.LastIndexOf("\\")-1));

stringfileNO=System.DateTime.Now.Year.ToString("00")+System.DateTime.Now.Month.ToString("00")+System.DateTime.Now.Day.ToString("00")+System.DateTime.Now.Hour.ToString("00")+System.DateTime.Now.Minute.ToString("00")+System.DateTime.Now.Second.ToString("00")+"_"+WWID;

//临时存放
stringsFileSavePath=Server.MapPath("upload")+"\\"+fileNO+ext;
//保存文件
this.myFile.PostedFile.SaveAs(sFileSavePath);
DataSetdt=newDataSet();
try
{
if(ext==".xls")
{
xlconn=newOleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;DataSource='"+sFileSavePath+"';ExtendedProperties=\"Excel8.0;HDR=YES;IMEX=1\"");
}
else
{
xlconn=newOleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;DataSource='"+sFileSavePath+"';ExtendedProperties=\"Excel12.0Xml;HDR=YES;IMEX=1\"");
}
}
catch(Exceptionex)
{
this.PageAlert(ex.Message);
return;
}
stringsheetName="店面SR模板";
try
{
//获取数据保存到DataSet
xlda=newOleDbDataAdapter("select*from["+sheetName+"$]",xlconn);
xlda.Fill(dt);
}
catch
{
Response.Write("<scripttype='text/javascript'>alert('请核对模板是否正确!');</script>");
errData.Text="";
return;
}
finally
{
xlconn.Close();
xlda.Dispose();
}
SqlConnectionconn=newSqlConnection(connString);
SqlCommandcmd=newSqlCommand();
cmd.CommandType=CommandType.Text;
cmd.Connection=conn;

try
{
intcount=dt.Tables[0].Rows.Count;
intnumber=1;
if(CheckTemplate(dt.Tables[0]))
{
StringBuildersql=newStringBuilder();
sql.Append("setNOCOUNTON"+"\n");
sql.Append("INSERTINTOprc_xoem_stor_sr_data_raw(stor_id,slsprs_id,slsprs_nm,lst_upt_dtm)\n");

foreach(DataRowdrindt.Tables[0].Rows)
{
stringstor_id="'"+dr[0].ToString().Trim()+"'";
stringslsprs_id="'"+dr[1].ToString().Trim()+"'";
stringslsprs_nm="'"+dr[2].ToString().Trim()+"'";
stringupload_tm="'"+DateTime.Now.ToString("yyyy-MM-dd")+"'";

if(number==count)
{
sql.Append("select"+stor_id+","+slsprs_id+","+slsprs_nm+","+upload_tm+"\n");
}
else
{
sql.Append("select"+stor_id+","+slsprs_id+","+slsprs_nm+","+upload_tm+"UNIONALL"+"\n");
}

number++;
}
sql.Append("setNOCOUNTOFF"+"\n");
conn.Open();
cmd.CommandTimeout=300;
cmd.CommandText=sql.ToString();
cmd.ExecuteNonQuery();
}
else
{
this.PageAlert("上传失败");
errData.Text="";
return;
}
}
catch(Exceptionex)
{
this.PageAlert(ex.Message);
return;
}
finally
{
conn.Close();
cmd.Dispose();
}

//执行脚本导入数
ExcuteProcedure();

//返回错误数据
BindERData();

//防止缓存
//Session.Remove(tableName);
ViewState["table"]=null;
ViewState["table"]=Err_dt;

if(Err_dt!=null)
{
errData.Text=string.Format("{0}",int.Parse(Err_dt.Rows.Count.ToString()));
}
else
{
errData.Text=string.Format("{0}",0);
}

intsuccessCount=dt.Tables[0].Rows.Count-Err_dt.Rows.Count;
this.PageAlert("更新成功"+successCount+"条,失败"+errData.Text+"条。");

}

privatevoidBindERData()
{
SqlConnectionconn=newSqlConnection(connString);
StringBuildersql=newStringBuilder();
sql.Append("selecta.Category+':'+a.RemarkaserrorMsg,b.*INTO#stor_srFROMprc_xoem_stor_sr_data_loga");
sql.Append("INNERJOINprc_xoem_stor_sr_data_rawbONa.data_id=b.idWHEREa.errorFlag=0ANDa.Category='导入失败'");
sql.Append("UPDATEprc_xoem_stor_sr_data_logSETerrorFlag=1WHERECategory='导入失败'");
sql.Append("SELECT*FROM#stor_sr");
try
{
conn.Open();
Err_dt=SqlHelper.ExecuteDataset(conn,CommandType.Text,sql.ToString()).Tables[0];
GridMain.DataSource=Err_dt;
GridMain.DataBind();
}
catch(Exceptionex)
{
this.PageAlert(ex.Message);
Err_dt=null;
GridMain.DataSource=Err_dt;
GridMain.DataBind();
}
finally
{
conn.Close();
}

}
///<summary>
///执行更新店面SR
///</summary>
privatevoidExcuteProcedure()
{
SqlConnectionconn=newSqlConnection(connString);
SqlCommandcmd=newSqlCommand();
cmd.CommandTimeout=6000000;
cmd.CommandText="prc_xoem_stor_sr_update";
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=conn;

stringupdate_dtm=DateTime.Now.ToString("yyyy-MM-dd");
try
{
cmd.Parameters.AddWithValue("@yyyydd",update_dtm);
conn.Open();
cmd.ExecuteNonQuery();
}
catch(Exceptionex)
{
this.PageAlert(ex.Message);
}
finally
{
conn.Close();
cmd.Dispose();
}

}
///<summary>
///验证模板列名是否正确
///</summary>
///<paramname="dataTable"></param>
///<returns></returns>
privateboolCheckTemplate(DataTabledt)
{
boolboolResult=true;
stringmsg=string.Empty;
List<string>list=newList<string>();
for(inti=0;i<dt.Columns.Count;i++)
{
list.Add(dt.Columns[i].ColumnName);
}
try
{
if(list[0].ToString().Trim()!="StoreID")
{
msg="第A列应该为:StoreID";
this.PageAlert(msg);
boolResult=false;
}
if(list[1].ToString().Trim()!="SRID")
{
msg="第B列应该为:SRID";
this.PageAlert(msg);
boolResult=false;
}
if(list[2].ToString().Trim()!="SRName")
{
msg="第C列应该为:SRName";
this.PageAlert(msg);
boolResult=false;
}
}
catch
{
this.PageAlert("请核对模板是否正确");
boolResult=false;
}
returnboolResult;
}

protectedvoidbtnExport_Click(objectsender,EventArgse)
{
GridMain.AllowPaging=false;
GridMain.AllowSorting=false;

bindNextPage(0);

Export(GridMain,"StoreSRErrorList.xls","StoreSRErrorList","application/ms-excel");

GridMain.AllowPaging=true;
GridMain.AllowSorting=false;

}

#regionExporttotheexcel

//Exporttotheexcel
privatevoidExport(System.Web.UI.WebControls.DataGriddg,stringfileName,stringfn,stringtypeName)
{
System.Web.HttpResponsehttpResponse=Page.Response;
httpResponse.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8));
httpResponse.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
httpResponse.ContentType=typeName;
System.IO.StringWritertw=newSystem.IO.StringWriter();
System.Web.UI.HtmlTextWriterhw=newSystem.Web.UI.HtmlTextWriter(tw);
dg.RenderControl(hw);

//httpResponse.Write(tw.ToString());
//httpResponse.End();
stringfilePath=Server.MapPath("..")+fn+DateTime.Now.Ticks.ToString()+newRandom().Next(100).ToString();
System.IO.StreamWritersw=System.IO.File.CreateText(filePath);
sw.Write(tw.ToString());
sw.Close();
DownFile(httpResponse,fileName,filePath);

httpResponse.End();
}

privateboolDownFile(System.Web.HttpResponseResponse,stringfileName,stringfullPath)
{
System.IO.FileStreamfs=System.IO.File.OpenRead(fullPath);
try
{
Response.ContentType="application/octet-stream";

Response.AppendHeader("Content-Disposition","attachment;filename="+
HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8)+";charset=GB2312");
//System.IO.FileStreamfs=System.IO.File.OpenRead(fullPath);
longfLen=fs.Length;
intsize=102400;//每100K同时下载数据
byte[]readData=newbyte[size];//指定缓冲区的大小
if(size>fLen)size=Convert.ToInt32(fLen);
longfPos=0;
boolisEnd=false;
while(!isEnd)
{
if((fPos+size)>fLen)
{
size=Convert.ToInt32(fLen-fPos);
readData=newbyte[size];
isEnd=true;
}
fs.Read(readData,0,size);//读入一个压缩块
Response.BinaryWrite(readData);
fPos+=size;
}
fs.Close();
FileInfoFI=newFileInfo(fullPath);
if(FI.Exists)
{
FI.Delete();
}
returntrue;
}
catch
{
returnfalse;
}
finally
{
fs.Close();
}
}

#endregion

///<summary>
///提示代码
///</summary>
///<paramname="msg"></param>
privatevoidPageAlert(stringmsg)
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(),"Alert","<scripttype='text/javascript'>alert('"+msg+"')</script>");
}

protectedvoidGridMain_SelectedIndexChanged(objectsender,EventArgse)
{

}

}
}





                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: