gridview,datalist导入数据,导出数据

导入数据,导出数据
------------------------------------------------------------
protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.PostedFile.FileName.ToString() != "" && FileUpload1.PostedFile.FileName.ToString().Substring((FileUpload1.PostedFile.FileName.ToString().Length - 3), 3) == "xls")
        {
            string strFileName;
            DateTime mydatetime = new DateTime();
            mydatetime = DateTime.Now;
            strFileName = mydatetime.Year.ToString() + mydatetime.Month.ToString() + mydatetime.Day.ToString() +
                mydatetime.Hour.ToString() + mydatetime.Minute.ToString() + mydatetime.Second.ToString() + ".xls";
            string path = HttpContext.Current.Server.MapPath("Temp//");
            FileUpload1.SaveAs(path + strFileName);

            //写一个Updata方法,用来在数据库中添加数据
            Update(path + strFileName);
            Response.Write("<script>alert('导入成功');</script>");
        }
        else
        {
            Label1.Text = "请选择一个Execl文件!";
        }
        BindExecl();
    }

    GetData GD = new GetData();
    string sql;
    DataSet ds;
    /// <summary>
    /// 添加数据
    /// </summary>
    /// <param name="UploadFileName"></param>
    private void Update(string UploadFileName)
    {
        string OleDbstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + UploadFileName + "';Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
        OleDbConnection OleDbcon = new OleDbConnection();
        OleDbcon.ConnectionString = OleDbstr;
        OleDbcon.Open();
        OleDbCommand OleDbcomm = new OleDbCommand("select * from [shopclass$]", OleDbcon);
        OleDbDataAdapter da = new OleDbDataAdapter();
        da.SelectCommand = OleDbcomm;
        DataSet ds = new DataSet();
        DataTable myTable = ds.Tables.Add("shopclass$");
        da.Fill(ds, "shopclass$");
        OleDbcon.Close();
        int shopClassid;
        //int id;
        shopClassid = GD.MaxShopClassId() + 1;
        for (int i = 0; i < myTable.Rows.Count; i++)
        {
            SqlConnection conn = GD.Conn();
            //string sql = "insert into execl(shopClassid,name,father,userId) values('" + myTable.Rows[i][0].ToString() + "','" + myTable.Rows[i][1].ToString() + "','" + myTable.Rows[i][2].ToString() + "'," + 1 + ")";
            sql = "insert into execl(shopClassid,name,father,userId) values('" + shopClassid + "','" + myTable.Rows[i][1].ToString() + "','" + myTable.Rows[i][2].ToString() + "'," + 1 + ")";
            SqlCommand cmd = new SqlCommand(sql, conn);
            //id = shopClassid + 1;
            shopClassid++;
            conn.Open();
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.ToString());
            }
            finally
            {
                conn.Close();               
            }
        }
    }

    /// <summary>
    /// 导出到Execl表事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        Export("application/ms-excel", "宠物类别表.xls");
    }

    /// <summary>
    /// 导出到Execl表方法
    /// </summary>
    /// <param name="FileType"></param>
    /// <param name="FileName"></param>
    private void Export(string FileType, string FileName)
    {
        BindExecl2();

        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        //错误提示:只能在执行 Render() 的过程中调用 RegisterForEventValidation;
        //解决方法:EnableEventValidation = "false"
        GridView2.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }

 

--------------------------------------------------------------------
DataList数据输出到Excel
Repeater、DataList、DataGrid、GridView...还是比较喜欢用轻量级的数据绑定控件,本例事将DataList中的数据导入到Excel,以及一些相关操作;

MyTest.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyTest.aspx.cs" Inherits="MyWeb.MyTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
     <title>DataList数据输出到Excel</title>
</head>
<body>
     <form id="form1" runat="server">
     <div>
         <asp:DataList ID="dlMain" runat="server" OnItemDataBound="dlMain_ItemDataBound" OnCancelCommand="dlMain_CancelCommand" OnDeleteCommand="dlMain_DeleteCommand" OnEditCommand="dlMain_EditCommand" OnPreRender="dlMain_PreRender" OnUpdateCommand="dlMain_UpdateCommand" DataKeyField="IDCard" >
             <HeaderTemplate>
                 <asp:Table ID="tbHeader" runat="server">
                     <asp:TableRow>
                         <asp:TableCell Width="150px">IDCard</asp:TableCell>
                         <asp:TableCell Width="100px">Name</asp:TableCell>
                         <asp:TableCell Width="300px">Password</asp:TableCell>
                         <asp:TableCell Width="100px">Phone</asp:TableCell>
                     </asp:TableRow>
                 </asp:Table>
             </HeaderTemplate>
            <ItemTemplate>
                 <asp:Table ID="tbItem" runat="server">
                     <asp:TableRow>
                         <asp:TableCell Width="150px"><asp:Label ID="lblIDCard" runat="server" Text='<%#Eval("IDCard") %>'></asp:Label></asp:TableCell>
                         <asp:TableCell Width="100px"><%#Eval("name") %></asp:TableCell>
                         <asp:TableCell Width="300px"><%#Eval("pwd") %></asp:TableCell>
                         <asp:TableCell Width="100px"><%#Eval("phone") %></asp:TableCell>
                         <asp:TableCell>
                             <asp:LinkButton ID="lbtnView" runat="server" CommandArgument="ReadOnly" CommandName="Edit">查看</asp:LinkButton>
                         </asp:TableCell>
                         <asp:TableCell><asp:LinkButton ID="lbtnEdit" runat="server" CommandName="Edit" >编辑</asp:LinkButton></asp:TableCell>
                         <asp:TableCell><asp:LinkButton ID="lbtnRemove" runat="server" CommandName="Delete">删除</asp:LinkButton></asp:TableCell>
                     </asp:TableRow>
                 </asp:Table>
            </ItemTemplate>
           <EditItemTemplate>
                <asp:Table ID="tbEditItem" runat="server">
                     <asp:TableRow>
                         <asp:TableCell>IDCard:</asp:TableCell>
                         <asp:TableCell><asp:Label ID="lblIDCard" runat="server" Text='<%#Eval("IDCard") %>'></asp:Label></asp:TableCell>
                     </asp:TableRow>
                     <asp:TableRow>
                         <asp:TableCell>姓名:</asp:TableCell>
                         <asp:TableCell><asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name") %>'></asp:TextBox></asp:TableCell>
                     </asp:TableRow>
                     <asp:TableRow>
                         <asp:TableCell>密码:</asp:TableCell>
                         <asp:TableCell><asp:TextBox ID="txtPwd" runat="server" Text='<%#Eval("pwd") %>' TextMode="password"></asp:TextBox></asp:TableCell>
                     </asp:TableRow>
                     <asp:TableRow>
                         <asp:TableCell>电话:</asp:TableCell>
                         <asp:TableCell><asp:TextBox ID="txtPhone" runat="server" Text='<%#Eval("phone") %>'></asp:TextBox></asp:TableCell>
                     </asp:TableRow>
                </asp:Table>
                 <asp:Table ID="tb" runat="server">
                     <asp:TableRow>
                         <asp:TableCell>
                             <asp:LinkButton ID="lbtnUpdate" runat="server" CommandName="Update">确定</asp:LinkButton>
                             <asp:LinkButton ID="lbtnCancel" runat="server" CommandName="Cancel">取消</asp:LinkButton>
                         </asp:TableCell>
                     </asp:TableRow>
               </asp:Table>
           </EditItemTemplate>
             <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
             <SelectedItemStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
             <AlternatingItemStyle BackColor="White" ForeColor="#284775" />
             <ItemStyle BackColor="#F7F6F3" ForeColor="#333333" />
             <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
         </asp:DataList>
         <asp:LinkButton ID="lbtnOutput" runat="server" OnClick="lbtnOutput_Click">输出到Excel</asp:LinkButton>
         <asp:Label ID="lblMessage" runat="server" Text="" ForeColor="Coral"></asp:Label>
       </div>
     </form>
</body>
</html>

MyTest.aspx.cs

using System;
using System.Data;
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.IO;
using System.Data.SqlClient;

namespace MyWeb
{
     public partial class MyTest : System.Web.UI.Page
     {
         private SqlConnection cn = sqlCon.con();
         private bool mbMainBind = false;

         protected void Page_Load(object sender, EventArgs e)
         {
             lblMessage.Text = "";
         }

         protected void dlMain_PreRender(object sender, EventArgs e)
         {
             if (!IsPostBack || mbMainBind) BindData();
             SetEditControls();
         }

         #region 函数

         private void SetEditControls()
         {
             if (dlMain.EditItemIndex == -1 || dlMain.Items.Count == 0) return;
             bool bReadOnly = Convert.ToBoolean(ViewState["EditReadOnly"]);
             DataListItem item = dlMain.Items[dlMain.EditItemIndex];
             SetChildControlsEnabled(item.FindControl("tbEditItem"), !bReadOnly);
             LinkButton lbtnUpdate = (LinkButton)item.FindControl("lbtnUpdate");
             lbtnUpdate.Enabled = !bReadOnly;

             TextBox txtPwd = (TextBox)item.FindControl("txtPwd");
             txtPwd.Attributes.Add("value", txtPwd.Text);

         }

         public static void SetChildControlsEnabled(Control ctlParent, bool bEnabled)
         {
             foreach (Control ctl in ctlParent.Controls)
             {
                 if (ctl is WebControl) ((WebControl)ctl).Enabled = bEnabled;
                 SetChildControlsEnabled(ctl, bEnabled);
             }
         }

         private void BindData()
         {
             cn.Open();
             string sSQL = "SELECT IDCard,name,pwd,phone FROM basic";
             SqlCommand cmd = new SqlCommand(sSQL, cn);
             SqlDataReader reader = cmd.ExecuteReader();
             dlMain.DataSource = reader;
             dlMain.DataBind();
             cn.Close();
         }

         #endregion

         protected void lbtnOutput_Click(object sender, EventArgs e)
         {
             Response.Clear();
             Response.Buffer = true;
             Response.Charset = "GB2312";
             Response.AppendHeader("Content-Disposition", "attachment;filename=Output.xls");
             Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
             Response.ContentType = "application/ms-excel";
             this.EnableViewState = false;
             System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
             StringWriter oStringWriter = new StringWriter(myCItrad);
             HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
             this.dlMain.RenderControl(oHtmlTextWriter);
             Response.Write(oStringWriter.ToString());
             Response.End();

         }

         #region 事件

         protected void dlMain_ItemDataBound(object sender, DataListItemEventArgs e)
         {
             if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem||e.Item.ItemType==ListItemType.EditItem)
             {
                 Label lblIDCard = (Label)e.Item.FindControl("lblIDCard");
                 lblIDCard.Attributes.Add("style", "vnd.ms-excel.numberformat:@");              
             }
             if (e.Item.ItemType == ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem)
             {
                 LinkButton lbtnRemove = (LinkButton)e.Item.FindControl("lbtnRemove");
                 lbtnRemove.Attributes.Add("onclick", "return confirm('确定要删除该记录?!');");
             }
         }

         protected void dlMain_CancelCommand(object source, DataListCommandEventArgs e)
         {
             dlMain.EditItemIndex = -1;
             mbMainBind = true;
         }

         protected void dlMain_DeleteCommand(object source, DataListCommandEventArgs e)
         {
             cn.Open();
             string sIDCard = dlMain.DataKeys[e.Item.ItemIndex].ToString();
             string sSQL = "DELETE FROM basic WHERE IDCard=@IDCard";
             SqlCommand cmd = new SqlCommand(sSQL, cn);
             cmd.Parameters.AddWithValue("@IDCard", sIDCard);
             try
             {
                 cmd.ExecuteNonQuery();
                 lblMessage.Text = "删除成功!";
             }
             catch (Exception ex)
             {
                 lblMessage.Text = ex.Message;
             }
             finally
             {
                 cn.Close();
             }
             mbMainBind = true;
         }

         protected void dlMain_EditCommand(object source, DataListCommandEventArgs e)
         {
             dlMain.EditItemIndex = e.Item.ItemIndex;
             if (e.CommandArgument.ToString() == "ReadOnly")
                 ViewState["EditReadOnly"] = true;
             else
                 ViewState["EditReadOnly"] = false;
             mbMainBind = true;
         }

         protected void dlMain_UpdateCommand(object source, DataListCommandEventArgs e)
         {
             string sIDCard = dlMain.DataKeys[e.Item.ItemIndex].ToString();

             TextBox txtName = (TextBox)e.Item.FindControl("txtName");
             TextBox txtPwd = (TextBox)e.Item.FindControl("txtPwd");
             TextBox txtPhone = (TextBox)e.Item.FindControl("txtPhone");

             string sName = txtName.Text.Trim();
             string sPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPwd.Text.Trim(), "MD5");
             string sPhone = txtPhone.Text.Trim();

             cn.Open();
             string sSQL = "UPDATE basic SET name=@name,pwd=@pwd,phone=@phone WHERE IDCard=@IDCard";
             SqlCommand cmd = new SqlCommand(sSQL, cn);
             cmd.Parameters.AddWithValue("@name", sName);
             cmd.Parameters.AddWithValue("@pwd", sPwd);
             cmd.Parameters.AddWithValue("@phone", sPhone);
             cmd.Parameters.AddWithValue("@IDCard", sIDCard);

             try
             {
                 cmd.ExecuteNonQuery();
                 lblMessage.Text = "更新成功!";
                 dlMain.EditItemIndex = -1;
             }
             catch (Exception ex)
             {
                 lblMessage.Text = ex.Message;
             }
             finally
             {
                 cn.Close();
             }
             mbMainBind = true;
         }

         #endregion

     }
}


数据库设计:

create database information
use information
create table [basic]
(
[IDCard] nvarchar(18) primary key,
[name] nvarchar(50),
[pwd] nvarchar(50),
[phone] nvarchar(20)
)
go
 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值