Monday, 3 September 2012

Read excel using C#,Update excel using C#,Display Excel in html table using c#

.CS Page. 

This is complete project

How will it works.
1) browse any xls and xlsx file and upload it.
2) All the uploaded files will show in a Table.
3) Select File that you want to open.after selection all the sheets of selected table will show.
4) Click on sheet name that u want to open.
5) Data of selected sheet will display in html table.
6) If u wanat to edit excel file u must add ID column in your Excel sheet this column must be numeric and unique.

may be u face some html or css issue in this project,just remove link of non existing css and jscript file.
may be u r unable to create connection with excel just go to following link and install access database engine.
http://www.microsoft.com/en-us/download/details.aspx?id=23734


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.OleDb;

public partial class ProductionIssueStatus : System.Web.UI.Page
{
    public DataSet dsSheets = null;
    //public DataTable dt = null;
    public DataTable dtSheeet = null;
    public bool isshowSheet = false;
    protected FileInfo[] rgFiles = new FileInfo[0];

    public System.Data.DataSet xlsInsert(string pth)
    {
        DataSet ds = new DataSet();
        string strcon = string.Empty;
        if (Path.GetExtension(pth).ToLower().Equals(".xls") ||
            Path.GetExtension(pth).ToLower().Equals(".xlsx"))
        {
            strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pth + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
            //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 = "";
        DataTable exDT = new DataTable();
        exDT.TableName = "aa";
        using (OleDbConnection excelCon = new OleDbConnection(strcon))
        {
            try
            {
                DataTable dtSheets = null;
                DataTable dtnew = null;
                excelCon.Open();
                DataTable dtschema = excelCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                foreach (DataRow dr in dtschema.Rows)
                {
                    if (!(Convert.ToString(dr["TABLE_NAME"]).IndexOf("FilterDatabase") > 0))
                    {
                        dtSheets = new DataTable();
                        dtSheets.TableName = dr["TABLE_NAME"].ToString();
                        strselect = "Select * from [" + dr["TABLE_NAME"].ToString() + "]";
                        using (OleDbDataAdapter exDA = new OleDbDataAdapter(strselect, excelCon))
                        {
                            exDA.Fill(dtSheets);

                            if (dtSheets.Rows.Count > 0)
                            {

                                dtnew = dtSheets.Clone();
                                if (dtnew.Columns.Contains("Created Time"))
                                {
                                    dtnew.Columns["Created Time"].DataType = typeof(DateTime);
                                    foreach (DataRow drnew in dtSheets.Rows)
                                    {
                                        dtnew.ImportRow(drnew);
                                    }
                                    DataView dv = dtnew.DefaultView;
                                    dv.Sort = "Created Time DESC";
                                    dtSheets = dv.ToTable();
                                }
                                else if (dtnew.Columns.Contains("CreatedTime"))
                                {
                                    dtnew.Columns["CreatedTime"].DataType = typeof(DateTime);
                                    foreach (DataRow drnew in dtSheets.Rows)
                                    {
                                        dtnew.ImportRow(drnew);
                                    }
                                    DataView dv = dtnew.DefaultView;
                                    dv.Sort = "CreatedTime DESC";
                                    dtSheets = dv.ToTable();
                                }

                            }

                        }
                        if (dtSheets != null && dtSheets.Rows.Count > 0)
                        {
                            ds.Tables.Add(dtSheets);
                        }
                    }                

                }
            }
            catch (OleDbException oledb)
            {
                throw new Exception(oledb.Message.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
            finally
            {
                excelCon.Close();
            }          
            if (ds == null || !(ds.Tables.Count > 0))
            {
                throw new Exception("File uploaded has no record found.");
            }
            foreach (DataTable dt in ds.Tables)
            {
                string name = dt.TableName;
            }
            return ds;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = "Production Support Issue Status";
        if (!IsPostBack)
        {
            ddlColumn.Items.Add("Select");
        }
        if (IsPostBack)
        {
            if (Request.Params.ToString().IndexOf("btnUpdate") > 0)
            {
                if (UpdateData())
                {
                    txtSNo.Value = "";
                    txtNewValue.Value = "";
                    string strScript = "";
                    strScript = "<script>";
                    strScript += "alert('Data Updated successfully');";
                    strScript += "</script>";
                    Page.RegisterStartupScript("strScript", strScript);
                }
                else
                {
                    txtSNo.Value = "";
                    txtNewValue.Value = "";
                    string strScript = "";
                    strScript = "<script>";
                    strScript += "alert('Id does not exist');";
                    strScript += "</script>";
                    Page.RegisterStartupScript("strScript", strScript);
                }
            }
        }
        int isRemove = 0;
        string SheetName = "";    
        string path = Server.MapPath("~/XlsUploadFile");
        DirectoryInfo di = new DirectoryInfo(path);
        rgFiles = di.GetFiles();
        string filename = Convert.ToString(Request.QueryString["fileName"]);
        SheetName = Convert.ToString(Request.QueryString["SheetName"]);
        if (SheetName != null && SheetName.Length > 0)
        {
            isshowSheet = true;
            filename = Convert.ToString(Session["CurrentFile"]);
        }
        Session["CurrentFile"] = filename;
        isRemove = Convert.ToInt32(Request.QueryString["Remove"]);
        if (filename != null && filename != "" && isRemove != 1)
        {
            lblSelectedFile.Text = filename;
            lblSelectedFile.Font.Bold = true;
            string uploadedFile = (Server.MapPath("~/XlsUploadFile/" + filename));
            try
            {
                dsSheets = xlsInsert(uploadedFile);
                if (isshowSheet)
                {
                    dtSheeet = dsSheets.Tables[SheetName];
                }
                ddlColumn.DataSource = getColumnList(dtSheeet);
                ddlColumn.DataTextField = "ColumnName";
                ddlColumn.DataValueField = "ColumnName";
                ddlColumn.DataBind();
                // EditableGrid();
            }
            catch (Exception)
            {
                //uplod = false;
                this.lblMessage.Text = "System uploading Error";
            }
        }
        if (isRemove == 1 && filename != null && filename != "")
        {
            File.Delete(Server.MapPath("~/XlsUploadFile/" + filename));
            Response.Redirect("ProductionIssueStatus.aspx");
        }
    }
    private DataTable getColumnList(DataTable dtSheeet)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ColumnName", typeof(string));
        DataRow dr;
        if (dtSheeet != null && dtSheeet.Rows.Count > 0)
        {
            dr = dt.NewRow();
            dr["ColumnName"] = "Select";
            dt.Rows.Add(dr);
            for (int i = 0; i < dtSheeet.Columns.Count; i++)
            {
                dr = dt.NewRow();
                dr["ColumnName"] = dtSheeet.Columns[i].ColumnName;
                dt.Rows.Add(dr);
            }
            return dt;
        }
        else
        {
            dr = dt.NewRow();
            dr["ColumnName"] = "Select";
            dt.Rows.Add(dr);
            return dt;
        }
    }
    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
                if (File.Exists(Server.MapPath("~/XlsUploadFile/" + xlsUpload.FileName.ToString())))
                {
                    File.Delete(Server.MapPath("~/XlsUploadFile/" + xlsUpload.FileName.ToString()));
                }
                xlsUpload.SaveAs(Server.MapPath("~/XlsUploadFile/" + xlsUpload.FileName.ToString()));
                string uploadedFile = (Server.MapPath("~/XlsUploadFile/" + xlsUpload.FileName.ToString()));
            }
            if (uplod)
            {
                string mess1 = "File has successfully uploaded";
                this.lblMessage.Text = mess1;
                Response.Redirect("ProductionIssueStatus.aspx");
            }
        }
        else
        {
            this.lblMessage.Text = "Please select file to upload.";
        }
    }
    public void MultiView(DataSet ds)
    {
     
    }  
    public bool UpdateData()
    {
        string backup = "";
        string pthForBackup = (Server.MapPath("~/Log/"));
        string filename = Convert.ToString(Session["CurrentFile"]);
        string SheetName = Convert.ToString(Request.QueryString["SheetName"]);
        string ID = txtSNo.Value;
        string ColumnName = ddlColumn.SelectedValue;
        string NewValue = txtNewValue.Value;
        DataTable dtBackup = new DataTable();
        if (filename.Length > 0 && SheetName.Length > 0)
        {
            string pth = (Server.MapPath("~/XlsUploadFile/" + filename));
            OleDbConnection excelCon = getConnection(pth);
            try
            {
                string strselect = " select " + ColumnName + " from [" + SheetName + "] where ID = " + ID + "";
                string str1 = "update [" + SheetName + "] set " + ColumnName + "='" + NewValue + "' where ID = " + ID + " ";
                OleDbCommand cmd;

                cmd= new OleDbCommand(str1, excelCon);
                excelCon.Open();

                using (OleDbDataAdapter adap = new OleDbDataAdapter(strselect, excelCon))
                {
                    adap.Fill(dtBackup);
                }
                if (dtBackup != null && dtBackup.Rows.Count > 0)
                {
                    string OldValue = Convert.ToString(dtBackup.Rows[0][ColumnName]);
                    backup = str1 + " <Old Value : " + OldValue + ">";
                }
                int rowsupdated = cmd.ExecuteNonQuery();
                if (rowsupdated > 0)
                {
                    backup = backup + "<Status : Success>";
                    backup = backup + "<updated by : " + clsIssueStatus.IPAddress() + ">";
                    clsIssueStatus.QueryLog(backup, pthForBackup);
                    return true;
                }
                else
                {
                    backup = str1;
                    backup = backup + "<Status : Unsuccess>";
                    backup = backup + "<Updated by : " + clsIssueStatus.IPAddress() + ">";
                    clsIssueStatus.QueryLog(backup, pthForBackup);
                    return false;
                }

            }
            catch (Exception ex)
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
     
    }
    public OleDbConnection getConnection(string PathOfXMLFileWithFileName)
    {
        string pth = PathOfXMLFileWithFileName;
        string strcon = string.Empty;
        if (Path.GetExtension(pth).ToLower().Equals(".xls") ||
            Path.GetExtension(pth).ToLower().Equals(".xlsx"))
        {
            strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pth + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
            //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;\"";
        }
        DataSet dtSheets = new DataSet();
        OleDbConnection excelCon = new OleDbConnection(strcon);
        return excelCon;
    }
}


.Aspx Page


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ProductionIssueStatus.aspx.cs"
    Inherits="ProductionIssueStatus" %>

<!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>Untitled Page</title>
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
table, tr, td, th{margin:0px; padding:0px;}
table.imagetable {
font-family: verdana,arial,sans-serif;
font-size:11px;
color:#333333;
border-width: 1px;
border-color: #999999;
border-collapse: collapse;
}
table.imagetable th {
background:#b5cfd2 url('cell-blue.jpg');
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #999999;
}
table.imagetable td {
background:#dcddc0 url('cell-grey.jpg');
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #999999;
}
table.sortable thead {
    background-color:#eee;
    color:#666666;
    font-weight: bold;
    cursor: pointer;
}

</style>

    <script type="text/javascript" language="javascript">
    function Filter(columnNo,valToFilter)
{
//var table=document.getElementById("Table1");
var table = document.all("Table1");
fltr1=valToFilter.value;
for (var r = 1; r < table.rows.length; r++) {
            table.rows[r].style.display = '';
        }
        for (var r = 1; r < table.rows.length; r++) {    
        ele1  = table.rows[r].cells[Number(columnNo)+1];
        ele1 = String(ele1.innerText);
        if (fltr1.length > 0) {    
     
        if (ele1.toLowerCase().indexOf(fltr1) >= 0 && table.rows[r].style.display == '') {
                        table.rows[r].style.display = '';
                    }
                    else if (table.rows[r].style.display == '') {
                        table.rows[r].style.display = 'none';
                    }
     
        }
     
        }

}

    </script>

    <script type="text/javascript" src="sorttable.js"></script>

</head>
<body>
    <form id="form1" runat="server">
        <div class="logo">
            <img src="images/logo.png" alt="Travel Boutique online" title="Travel Boutique online"></div>
        <div style="position: relative;">
            <div>
                <table>
                    <tr>
                        <td>
                            <asp:Label ID="label1" runat="server" Text="Choose File" Font-Bold="true"></asp:Label>
                            <asp:FileUpload ID="xlsUpload" runat="server" Font-Size="Small" />
                        </td>
                        <td>
                            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                        </td>
                        <td>
                            <asp:Label ID="lblMessage" runat="server" Text="" ForeColor="Red"></asp:Label>
                        </td>
                    </tr>
                </table>
            </div>
            <div style="margin: 5px">
                <div>
                    <span>
                        <br />
                        <span><b>List of files</b> :<br />
                            <br />
                        </span></span>
                </div>
                <table class="imagetable">
                    <tr>
                        <th>
                            Serial No.</th>
                        <th>
                            File Name</th>
                        <th>
                            Download</th>
                    </tr>
                    <%int i = 0; %>
                    <%foreach (System.IO.FileInfo fi in rgFiles)
                      {%>
                    <tr>
                        <td>
                            <%=++i%>
                        </td>
                        <td>
                            <a href="ProductionIssueStatus.aspx?fileName=<%=fi.Name %>">
                                <%=fi.Name%>
                            </a>
                        </td>
                        <td>
                            <%string Filepath = "XlsUploadFile/" + fi.Name;%>
                            <a href="<%=Filepath%>">Download</a>
                        </td>
                    </tr>
                    <%} %>
                </table>
            </div>
            <div>
                <br />
                <asp:Label ID="lblSelectedFile" runat="server"></asp:Label>
                <br />
                <br />
            </div>
            <div>
                <input type="button" onclick="ShowBlock()" style="float: right; margin-right: 10px;"
                    value="Update Data" />
            </div>
            <div id="updateBlock" style="position: absolute; left: 900px; right:100px; top: 10px; display: none;
                background-color: #FFF; border: 1px dashed #000;">
                <div class="form">
                    <div style="float: right; margin-right: 5px; cursor: pointer;" onclick="HideBlock()">
                        [ X ]</div>
                    <div style="margin: 10px 0px 10px 0px;">
                    </div>
                    <div style="margin-left: 5px">
                        <span>
                            <label>
                                ID :</label>
                            <input type="text" onkeypress="validate(event)" id="txtSNo" runat="server" />
                        </span><span>
                            <label>
                                Select Column :</label>
                            <asp:DropDownList ID="ddlColumn" runat="server">
                            </asp:DropDownList>
                        </span><span>
                            <label>
                                New Value :</label>
                            <input type="text" id="txtNewValue" runat="server" />
                        </span><span>
                            <label>
                            </label>
                            <asp:Button Height="23px" ID="btnUpdate" OnClientClick="return CheckData()" runat="server" Text="Update"
                                OnClick="btnUpdate_Click" />
                        </span>
                    </div>
                </div>
            </div>
            <div>
                <table class="imagetable">
                    <tr>
                        <%if (dsSheets != null)
                          { %>
                        <%foreach (System.Data.DataTable dt in dsSheets.Tables)
                          { %>
                        <th>
                            <a href="ProductionIssueStatus.aspx?SheetName=<%=dt.TableName %>" title="Click here to open sheet">
                                <%=dt.TableName.Remove(dt.TableName.IndexOf("$"))%>
                            </a>
                        </th>
                        <%} %>
                        <%} %>
                    </tr>
                </table>
            </div>
            <div style="width: 100%; margin: 20px 5px 0px 5px;">
                <%if (dtSheeet != null)
                  {%>
                <table class="sortable imagetable" id="Table1">
                    <%int SNo = 0; %>
                    <tr>
                        <th title="Click here to sort">
                            SNo.</th>
                        <% for (int j = 0; j < dtSheeet.Columns.Count; j++)
                           {%>
                        <th title="Click here to sort">
                            <%=dtSheeet.Columns[j].ColumnName%>
                            <!-- <br />
                        <input type="text" title="Write to filter" style="width: 100%;" onkeyup="Filter('<%=j %>',this);" /> -->
                        </th>
                        <%} %>
                    </tr>
                    <%foreach (System.Data.DataRow dr in dtSheeet.Rows)
                      {%>
                    <tr id="<%=SNo %>">
                        <td>
                            <%=++SNo %>
                        </td>
                        <% for (int j = 0; j < dtSheeet.Columns.Count; j++)
                           {%>
                        <td>
                            <%if (dr[j].ToString().Length > 200)
                              { %>
                            <%dr[j] = dr[j].ToString().Substring(0, 200); %>
                            <%} %>
                            <%=dr[j].ToString()%>
                        </td>
                        <%} %>
                    </tr>
                    <%} %>
                </table>
                <%} %>
            </div>
            <!-- Old Code -->
            <div runat="server" id="tab">
            </div>
        </div>
    </form>

    <script language="javascript" type="text/javascript">
    function CheckData()
    {
    debugger;
    var ddlcontrol=document.getElementById('<%=ddlColumn.ClientID %>');
    var ColumnName=ddlcontrol.options[ddlcontrol.selectedIndex].value;
    var sno= document.getElementById('<%=txtSNo.ClientID %>').value;
    var NewValue= document.getElementById('<%=txtNewValue.ClientID %>').value;
    if(sno.length>0)
    {}
    else
    {
    alert("Enter ID.");
    return false;
    }
 
    if(ColumnName=='Select')
    {
    alert("Select Column");
    return false;
    }  
 
     if(NewValue.length>0)
    {}  
    else
    {
    alert("Enter New value");
    return false;
    }
    return true;
    }
       
    function HideBlock()
    {
    document.getElementById("updateBlock").style.display='none';  
    }
    function ShowBlock()
    {
    document.getElementById("updateBlock").style.display='block';  
    }
    function validate(evt) {
if(evt.keyCode==8 || evt.keyCode==9)
{}
else
{
        var theEvent = evt || window.event;
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode( key );
        var regex = /[0-9]|\./;
        if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault)
        theEvent.preventDefault();
        }
         }
       }    
    </script>

</body>
</html>



No comments:

Post a Comment