65.9K
CodeProject 正在变化。 阅读更多。
Home

将 Excel 电子表格文件上传到服务器,然后在 Gridview 中显示记录

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.25/5 (6投票s)

2012年1月16日

CPOL

1分钟阅读

viewsIcon

76284

downloadIcon

4631

将 Excel 电子表格文件上传到服务器,然后在 Gridview 中显示记录

sample_screen_input_output_small.jpg

引言

不久前,我有一个任务是开发一个模块,用于将 Excel 电子表格记录上传到数据库目标表。 在将其保存到该表之前,要求首先将所有记录(行)显示在网格视图中。 此外,如果 Excel 文件第一列为空,则不应将其包含在 Grid View 中。 另一个要求是,如果将其安装在远程服务器上,则不应遇到任何安全访问权限之类的错误。 我在这个网站上搜索过,但没有找到任何具有此类相关要求的文章,因此我想分享这些内容。

让我们开始吧。

在客户端代码中

创建一个用于上传文件按钮的区域

<div>
   <asp:Label ID="label1" runat="server" Text="File"></asp:Label>
      
     <asp:FileUpload ID="xlsUpload" runat="server" Font-Size="Small" />
</div>
<div>
    <table width="100%">
       <tr align="left">
          <td>
             <asp:Button ID="btnUpload" runat="server" Text="Upload" 
        OnClick="btnUpload_Click" />
           </td>
       </tr>
    </table>
</div>

创建一个用于消息框标签的区域

<div>
   <table width="100%">
     <tr align="left">
        <td>
           <asp:Label ID="lblMessage" runat="server" Text="" ForeColor="Red"></asp:Label>
        </td>
     </tr>
   </table>
</div>

创建一个用于 Grid view 的区域

<div style="margin-top: 20px;">
    <table>
         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
             CellPadding="4" ForeColor="#333333" >
             <PagerSettings FirstPageText="" LastPageText="" NextPageText="" />
             <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
             <Columns>
                 <asp:BoundField DataField="CardNo" HeaderText="Card No" />
                 <asp:BoundField DataField="MemberName" HeaderText="Member Name" />
             </Columns>
             <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
             <PagerStyle BackColor="#FFCC66" 
        ForeColor="#333333" HorizontalAlign="Center" />
             <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
             <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
             <AlternatingRowStyle BackColor="White" />
          </asp:GridView>
    </table>
</div>

在代码隐藏文件中

它们非常简单,事实上我认为下面的代码中的注释已经足够详细地解释了它们。 所以我不会用更多的解释性文字来烦你,因为它很清楚。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Data.OleDb;

namespace ExcelToGridview
{
    public partial class ExcelToGrid : System.Web.UI.Page
    {
        DataTable dt = null;

        public System.Data.DataTable xlsInsert(string pth)
        {
            string strcon = string.Empty;
            if (Path.GetExtension(pth).ToLower().Equals(".xls") ||
                Path.GetExtension(pth).ToLower().Equals(".xlsx"))
            {
                strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
                                + pth +
                                ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
            }
            else
            {
                strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
                              + pth +
                              ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
            }
            string strselect = "Select * from [Sheet1$]";
            DataTable exDT = new DataTable();
            using (OleDbConnection excelCon = new OleDbConnection(strcon))
            {
                try
                {
                    excelCon.Open();
                    using (OleDbDataAdapter exDA = 
            new OleDbDataAdapter(strselect, excelCon))
                    {
                        exDA.Fill(exDT);
                    }
                }
                catch (OleDbException oledb)
                {
                    throw new Exception(oledb.Message.ToString());
                }
                finally
                {
                    excelCon.Close();
                }
                for (int i = 0; i < exDT.Rows.Count; i++)
                {
                    // Check if first column is empty
                    // If empty then delete such record
                    if (exDT.Rows[i]["CardNo"].ToString() == string.Empty)
                    {
                        exDT.Rows[i].Delete();
                    }
                }
                exDT.AcceptChanges();  // refresh rows changes
                if (exDT.Rows.Count == 0)
                {
                    throw new Exception("File uploaded has no record found.");
                }
                return exDT;
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (xlsUpload.HasFile)
            {
                bool uplod = true;
                string fleUpload = Path.GetExtension(xlsUpload.FileName.ToString());
                if (fleUpload.Trim().ToLower() == ".xls" | 
            fleUpload.Trim().ToLower() == ".xlsx")
                {
                    // Save excel file into Server sub dir
                    // to catch excel file downloading permission
                    xlsUpload.SaveAs(Server.MapPath("~/XlsUploadFile/" +
                        xlsUpload.FileName.ToString()));
                    string uploadedFile = (Server.MapPath("~/XlsUploadFile/" +
                        xlsUpload.FileName.ToString()));
                    try
                    {
                        dt = xlsInsert(uploadedFile);
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                    }
                    catch (Exception)
                    {
                        uplod = false;
                        this.lblMessage.Text = "System uploading Error";
                    }
                    File.Delete(uploadedFile); // Delete upload Excel
                            //file in sub dir 'lsUploadFile' no need to keep...
                }
                if (uplod)
                {
                    string mess1 = "File has successfully uploaded";
                    this.lblMessage.Text = mess1;
                }
            }
            else
            {
                this.lblMessage.Text = "Please select file to upload.";
            }

        }
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

关注点

本文的作者描述了如何将 Excel 电子表格文件上传到服务器,然后在 Gridview 中显示记录的技术用法。

我希望这篇文章对您有所帮助,感谢您的阅读。

© . All rights reserved.