如何将excel导入gridvieww中的数据导入到excel中

1)">1)">1" ng-class="{current:{{currentPage==page}}}" ng-repeat="page in pages"><li class='page' ng-if="(endIndex<li class='page next' ng-if="(currentPage
相关文章阅读温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
喜欢接触新鲜事物!
LOFTER精选
阅读(428)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
loftPermalink:'',
id:'fks_',
blogTitle:'C#將GridView中數據導入EXCEL',
blogAbstract:'&&& public override void VerifyRenderingInServerForm(Control control)&&& { }\r\n&&& protected void GridViewToExcel(GridView Gdv, string stitle)&&& {&&&&&&& Response.Clear();&&&&&&& Response.Buffer =&&&&&&& Response.Charset = \"GB2312\";',
blogTag:'',
blogUrl:'blog/static/',
isPublished:1,
istop:false,
modifyTime:0,
publishTime:7,
permalink:'blog/static/',
commentCount:0,
mainCommentCount:0,
recommendCount:0,
bsrk:-100,
publisherId:0,
recomBlogHome:false,
currentRecomBlog:false,
attachmentsFileIds:[],
groupInfo:{},
friendstatus:'none',
followstatus:'unFollow',
pubSucc:'',
visitorProvince:'',
visitorCity:'',
visitorNewUser:false,
postAddInfo:{},
mset:'000',
remindgoodnightblog:false,
isBlackVisitor:false,
isShowYodaoAd:false,
hostIntro:'喜欢接触新鲜事物!\r\n',
hmcon:'0',
selfRecomBlogCount:'0',
lofter_single:''
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}Excel数据导入到GridView中
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &图一 未导入Excel数据前的GridView&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &图二 导入的Excel数据文件&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&图三 导入后的GridView&
第一步 前台主要代码
&asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"ForeColor="#333333" Font-Size="14px" AllowPaging="True" PageSize="10" OnDataBound="NewPage"DataKeyNames="studentId" OnRowDeleting="GridView1_RowDeleting"&&FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /&&RowStyle BackColor="#EFF3FB" /&&Columns&&asp:TemplateField HeaderText="学生ID"&&ItemTemplate&&asp:Label ID="Label1" runat="server" Text='&%# Eval("studentId") %&' Width="80px"&&/asp:Label&&/ItemTemplate&&/asp:TemplateField&&asp:TemplateField HeaderText="姓名"&&ItemTemplate&&asp:Label ID="Label2" runat="server" Text='&%# Eval("name") %&' Width="60px"&&/asp:Label&&/ItemTemplate&&/asp:TemplateField&&asp:TemplateField HeaderText="专业"&&ItemTemplate&&asp:Label ID="Label3" runat="server" Text='&%# Eval("subject") %&' Width="60px"&&/asp:Label&&/ItemTemplate&&/asp:TemplateField&&asp:TemplateField HeaderText="学院"&&ItemTemplate&&asp:Label ID="Label4" runat="server" Text='&%# Eval("college") %&' Width="75px"&&/asp:Label&&/ItemTemplate&&/asp:TemplateField&&asp:TemplateField HeaderText="手机号"&&ItemTemplate&&asp:Label ID="Label5" runat="server" Text='&%# Eval("cellphone") %&' Width="80px"&&/asp:Label&&/ItemTemplate&&/asp:TemplateField&&asp:TemplateField HeaderText="邮箱"&&ItemTemplate&&asp:Label ID="a" runat="server" Text='&%# Eval("email") %&' Width="120px"&&/asp:Label&&/ItemTemplate&&/asp:TemplateField&&asp:TemplateField ShowHeader="False"&&ItemTemplate&&asp:Button ID="Button1" CssClass="btn" runat="server" CommandName="delete" Text="删除" /&&/ItemTemplate&&ControlStyle BackColor="#FFC0C0" /&&ItemStyle HorizontalAlign="Center" /&&/asp:TemplateField&&/Columns&&PagerTemplate&&asp:Table ID="Table1" Width="100%" runat="server"&&asp:TableRow&&asp:TableCell Width="200px"&&asp:Label ID="lblMessage" ForeColor="Blue" Text="请选择页码:" runat="server" CssClass="bottom" /&&asp:DropDownList ID="myDropDownList" AutoPostBack="true" OnSelectedIndexChanged="ChangePage"runat="server" /&&asp:LinkButton ID="btnPrev" Style="text-decoration: none" OnClick="ChangePage" runat="server"Text="上一页"&&/asp:LinkButton&&asp:LinkButton ID="btnNext" Style="text-decoration: none" OnClick="ChangePage" runat="server"Text="下一页"&&/asp:LinkButton&&/asp:TableCell&&asp:TableCell Width="200px" HorizontalAlign="right"&&asp:Label ID="lblPageLabel" ForeColor="Blue" runat="server" Width="200px" /&&/asp:TableCell&&/asp:TableRow&&/asp:Table&&/PagerTemplate&&PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /&&SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /&&HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /&&EditRowStyle BackColor="#2461BF" /&&AlternatingRowStyle BackColor="White" /&&/asp:GridView&&div&&span style="font-weight:bold"&批量导入&/span&&/div&&div&&span style="width:100px"&选择Excel文件&/span&&asp:FileUpload ID="fudExcel" runat="server" /&&asp:ButtonID="Button2" runat="server" Text="上传" onclick="Button2_Click" /&&asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/upload/学生信息导入模板.xls" Font-Size="XX-Small"&下载导入模板&/asp:HyperLink&&/div& &/div&
第二步 后台主要代码
/// &summary&/// 读取Excel数据/// &/summary&/// &param name="filepath"&&/param&/// &returns&&/returns&public DataTable ExcelDataSource(string filepath, ref bool existsSheetname){DataTable dt = null;string sheetname = "Sheet1$";string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";OleDbConnection conn = new OleDbConnection(strConn);conn.Open();DataTable sheetNames = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });conn.Close();// 获取第0个sheetif (sheetNames.Rows.Count & 0){foreach (DataRow row in sheetNames.Rows){if (row[2].ToString() == sheetname){existsSheetname = true;break;}}}if (existsSheetname){OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetname + "]", strConn);dt = new DataTable();dt.Columns.Add(new DataColumn("studentId"));dt.Columns.Add(new DataColumn("name"));dt.Columns.Add(new DataColumn("subject"));dt.Columns.Add(new DataColumn("college"));dt.Columns.Add(new DataColumn("cellphone"));dt.Columns.Add(new DataColumn("email"));oada.Fill(dt);}return}protected void Button2_Click(object sender, EventArgs e){#region 验证文件if (string.IsNullOrEmpty(fudExcel.FileName)){ScriptManager.RegisterStartupScript(this, this.GetType(), "updateScript", "alert(\"请选择上传文件 \");", true);return;}string extension = fudExcel.FileName.Substring(fudExcel.FileName.LastIndexOf('.'));if (extension == ".xlsx"){ScriptManager.RegisterStartupScript(this, this.GetType(), "updateScript", "alert(\"目前模板只支持Excel2003版文件,请转换后再导入!\");", true);return;}if (extension != ".xls"){ScriptManager.RegisterStartupScript(this, this.GetType(), "updateScript", "alert(\"上传文件扩展必须是(xls/xlsx)文件!\");", true);return;}#endregionstring filepath = string.E// 上传到服务器临时目录下string tempdir = Server.MapPath("../upload/");string filename = Guid.NewGuid() +filepath = tempdir +// 保存fudExcel.SaveAs(filepath);bool existsSheetname = false;// 读取到DataTablevar data = ExcelDataSource(filepath, ref existsSheetname);if (!existsSheetname){ScriptManager.RegisterStartupScript(this, this.GetType(), "updateScript", "alert(\"没有找到《模板工作表》工作表!\");", true);return;}// 删除临时文件System.IO.File.Delete(filepath);if (data == null){ScriptManager.RegisterStartupScript(this, this.GetType(), "updateScript", "解析Excel失败,请检查Excel是否符合模板要求!\");", true);return;}foreach (DataRow row in data.Rows){string id = row["studentId"].ToString();var arrRow = DataSource.Select("studentId='" + id + "'");if (arrRow != null && arrRow.Length & 0){}else{DataRow newrow = DataSource.NewRow();newrow["studentId"] = row["studentId"];newrow["name"] = row["name"];newrow["subject"] = row["subject"];newrow["college"] = row["college"];StudentsManage sm = new StudentsManage();if (sm.SelectByValue(newrow["studentId"].ToString()).Rows.Count == 0){students n = new students();n.StudentId = newrow["studentId"].ToString();n.Name = newrow["name"].ToString();n.Subject = newrow["subject"].ToString();n.College = newrow["college"].ToString();n.Cellphone = "";n.Creater = Session["adminId"].ToString();n.Pwd = newrow["studentId"].ToString();n.Email = "";n.Sex = "";sm.Insert(n);}StuCourseManage scm = new StuCourseManage();stuCourse m = new stuCourse();m.ClassId = Convert.ToInt32(Request.QueryString["classId"]);m.StudentId = newrow["studentId"].ToString();m.Creater = Session["adminId"].ToString();scm.InsertStu(m);}}gridviewBind();}
更加详细深入的分析请参考
阅读(...) 评论()

我要回帖

更多关于 c gridview导出excel 的文章

 

随机推荐