Sunday 2 April 2017

Top 10 SEO tips for your website


Top 10 SEO tips for your website

Improve your SEO using this top 10 tips and be found on all search engine and be always TOP on Search engine result.

Hi All, Today I will give Top 10 SEO tips for your website, this must be increase your visitors and improve SEO. And note one thing here Search engine strategy and rules are change frequently So you have to update your website as per new strategy.

Top 10 SEO tips for your website


1. Nice Domain name

Domain name should be readable, short and meaningful, It is not always correct. You can be avoid this tips if you have already domain name.

2. Purpose and design

You must be have answer for what's purpose of your site and who will visit your site. create website about one thing and content

3.keyword research

Always use keyword research tool when you adding new content in your page, just search on Google and check other competitors title and content. this will benefits how your title and content is proper.

4. Set the keywords in Title and content

Once you added new content in your page then after add your primary keywords in title and content. Do not add repeat keywords in Title or Metatag

5. Use pure HTML with no broken any tags

It is very important to HTML with no broken any tags, when search engine robots comes to your site then it will ignore your content if there is any broken tags.

6. Use H1 to H6 tag in your content

Set your page level keyword in H1 tag and all other should be use in title and subtitle of your content

7. Unique title and content for each page

You must be follow this to set up Unique title and content in each page. different title is very important to SEO.

8. Internal link and external link

You should have to set link in your one page to another page, you also be set the popular site link to your site.

9. update fresh content frequently

Search engine is always find new content and it is required to update your website content frequently

10. About and Contact us page

You should set your about page nad contact page link in home page, If possible to set 2 lines about your business to home page then do it.

Above all Top 10 SEO tips will increase your website visitors and improve SEO.


Now These all SEO tips is very small but effective to improve your SEO, You can't avoid these also.

11. Url should be short and readable

Your each page url should be short and readable not use ID in URL

12. Is Your website slow down?

If your website page speed is low then first improve page speed, Search engine not indexing your page if page speed is low. You must be remove anything that slows down your website and rebuild the features

13. Your website has to be single topic

Create website about one thing and 1 primary topics. Do not posting everything like news, blogs, education, entertainment in single website. Choose 1 nice thing and focus only on this site

14. Grammar mistake ?

Do not any mistake grammatically, this will stop the indexing. Make error free and grammatically mistake free page

15. Build internal link

It is very important to linking your internal pages to another page. check the Wikipedia website how they build internal link for each page. And also take note here link to other websites with relevant content only. Do not post your link to all website.

16. keywords in your images

You have to use your page level keywords in your images and also use the alt tag

17. Use rel="nofollow"

Add rel="nofollow" in a link for external link, Suppose you are using Wikipedia site as external site then you must set to nofollow for this link. This will tell search engine robot to no follow this link and continue on this.

18 Use rel="canonical" in all page

You need to set canonical url in head section, for duplicate content issue.

19. Make Subscribe Now form

Design this features and add Subscribe Now option to your website.

20. Use Comment functionality

Add Comment features in your website, it is very popular and user can give review.

21. Use sitemap in your website

Sitemap is a group of internal links of your website. Add 1 page Sitemap.html and set all important link here. Search engine first find this page and then starting to indexing your page

22. 404 - Use Not found page if not url Exist

You have to set up 404 page and redirect to this page if not found page. otherwise search engine as goes for duplicate content issue and leave indexing.

23. Error page

You should set up error page if any program error or any error and redirect to any custom page error.

24. Use Image tag with alt

Use image tag with alt and title, You can be set your primary or page level keyword to alt and image title. In every page you should use at least 1 image with alt and title, if more than 1 image than it will more help to you.

25. Use Date and Time at Top left corner

It is important to set Date and Time at Top left corner when created and updated this page. In Google search result page you show the date when this page created or updated if you have added date in page then search engine comes to again for indexing.

26. Use Breadcrumb in your page

Breadcrumb is a location of your current page, If you setup the proper Breadcrumb in your page then user can easily navigate to other page. Google store this Breadcrumb as Url and it will display to search engine result page.

27. Social networking

You must be setup the Social networking like Facebbok, Google+, LinkedIn and Twitter for your website. this will increase your referral website count and user comes from this Social networking

28. Use dash(-) in URL and image name

In every where You should use dash(-) rather than Underscore(_) like Url, Image or any static page name. Set proper image name about your page.
Example: best-top-10-seo-tips-for-your-website.jpg how-to-improve-seo-for-new-website.png

29. Capital letter in Url

Do not use capital letter in Url. It is best practice to use small letters in url

30. Popular website

Use at leaset 1 popular website in your page as external link this will tell search engine this site is trusted. and do not forgot to set nofollow here.

31. Relevant content in page

Ofcouse, You must be add proper content in page and Write like a human not for SEO only, do not add unnecessary content in your page so just add Relevant content in page

32. Do not checking Alexa rank daily

Do not waste time like this to checking Alexa rank, Alexa will auto update your rank when you are doing something on your site.

33. Site to all search engine

Some website tell you to "add your website here and we will submit your site to all search engine in 10 minute" Do not do this and do not waste your time.

34. Nice Design

Use nice font, font size, line height so user can ream more time in you wbsite and he/she might be interest to read more information.

35. Make your site Easy to navigation

Yes, this tips is very usefule to improve SEO, Your site must be Easy to navigation, user-friendly and Easy to use. So user can be read more time in your website

36. Hidden content

Do not use any hidden content with display:none, search engine easily detect this and it can be stop to indexing.

37. Become like brand

Become like brand and reputable websites so user can comes to again your website

38. Make your website mobile friendly and responsive

If your website is mobile friendly and responsive then user can read more information and easy to navigate other page using internal link. Do not use more advertisement banner in mobile site.

39. Learn from your best competitors

Yes, Always check your comptitors activity what they doing now and be updated to new things.

40. Write meaningful content with historical

Write well-researched and engaging content

41. Monitor your back-links

Check the backlinks from where users are coming to your site.

42. Get backlinks from relevant sites

Do not posting your site link to everywhere, post link to only reputed site and relevant site.


43. CSS and Javascript

You should not use inline css and Javascript, add css and Javascript code to another files and use reference to page. Avoid unnecessary code and comments from your Javascript codes.

44. use CDN server

If your website has too many images and it is slow to load than You have to use CDN server. CDN server is Content delivery network that loads images very fast. It will delivered content fast to the user.

45. Keyword stuffing

Don't do keyword stuffing, Do not add different primary keyword in same page.

46. Don't get purchase backlinks

Do not get or purchase backlinks from other, You also not get link from where more than 50 links already in that page. search engine ignore this type page.

47. reload convent or page refresh

Do not use any refresh function or reload convent in page automatically or redirection to other page.

48. Don't copy other website's content

Search engine easily detect as content is copied and it will not index your page.

49. Don't trust everything you read about SEO

As SEO strategy changing frequently and no anyone can now exact

50. Add files in Root folder

You must be add robots.txt and sitemap.xml in Root folder


These SEO tips will increase your rank in all search engine and effective, Comment here for any SEO related query.

Monday 27 March 2017

Owin Step By Step Token Based Authentication Using ASP.Net Web API

Step By Btep to Token Based Authentication Using ASP.Net Web API, OWIN




  • Step-1: Add webApi Project in visual studio 2015
  • Step-2: Setup the connection string in config file
  • Step-3: Add User class with Get and Set property
  • Step-4: Add AppDataConetext class file and add required method to validate user and get user details
  • Step-5: Add ApiController and add required method
  • Step-6: Change your ApplicationOAuthProvider.cs file
  • Step-7: Update ApplicationOAuthProvider.cs file


  • Add one more project to test your WebApi project with OWIN Authentication


  • Step-8: just add only 1 html file and required css and JS file.

  • Here I will explain how to Implement Token Based Authentication Using ASP.Net Web API and ajax post as client side. This is very important to implement Token Based Authentication in Web api project to security. Here I explained step by step to implement Token Based Authentication Using ASP.Net Web API. Try this and get security in your data. In previously I explained about Create Chat application in asp.net And Three tier architecture in asp.net For more example javascript and Asp.net


    Searches related to owin authentication web api example
    web api token based authentication example
    owin bearer token authentication with web api sample
    token based authentication using asp.net web api 2 owin and identity
    web api security token example
    web api token based authentication example c#
    Securing ASP.NET Web API using Token Based Authentication
    Implement Token Based Authentication Using ASP.Net Web API and ajax post as client side
    Implement Token Based Authentication with 2 separate project with custom table as login details and Authentication user
    Owin Step By Step Token Based Authentication Using ASP.Net Web API
    Token Based Authentication Using ASP.Net Web API, OWIN

    Now follow these step to security your web api with OWIN.

    Step-1. Add webApi Project in visual studio 2015

    Add webApi Project in visual studio 2015 and setup the name

    Step-2. Setup the connection string in config file

    You must be Setup the connectionstring in config file for database operation and user validate method

    Step-3. Add User.cs class with Get and Set property


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace API.Models
    {
        public class User
        {
            public int Id { get; set; }
            public string UserName { get; set; }
            public string Password { get; set; }
            public string Name { get; set; }
            public string MobileNo { get; set; }
            public string EmailId { get; set; }
            public string Country { get; set; }
            public string Address { get; set; }
            public string Hobbies { get; set; }
            public byte Gender { get; set; }
            public DateTime DateOfBirth { get; set; }
            public string BirthDate { get; set; }
            public string CountryName { get; set; }
            public string Search { get; set; }
            public string UserIds { get; set; }
      
    
            public string AuthenticationKey { get; set; }
        }
    }
    

    Step-4. Add AppDataConetext.cs file to database operation


    using System.Linq;
    
    using System.Data.Entity;
    
    namespace API.Models
    {
        public class AppDataConetext : DbContext
        {
    
            public AppDataConetext()
            :base("name=Conn")
            {
            }
    
            
            public User validateUser(string UserName,string Password)
            {
                User list = new User();
                list = Database.SqlQuery<User>("EXEC [ValidateUser] {0}, {1}", UserName, Password).FirstOrDefault();
                return list;
            }
            public User getUserById(int Id)
            {
                User list = new User();
                list = Database.SqlQuery<User>("EXEC [getUserById] {0}", Id).FirstOrDefault();
                return list;
            }
          
        }
    }
    

    Step-5. Add WebAPIController.cs and add required action method


    using API.Models;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.Owin.Security;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Security.Claims;
    using System.Security.Cryptography;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Http;
    using System.Web.Http.Cors;
    
    namespace API.Controllers
    {
        //[EnableCors(origins: "*", headers: "*", methods: "*")]
        //[Authorize]
        public class WebAPIController : ApiController
        {
            private const string LocalLoginProvider = "Local";
    
            AppDataConetext Db = new AppDataConetext();
    
            private IAuthenticationManager Authentication
            {
                get { return Request.GetOwinContext().Authentication; }
            }
    
            [Authorize]
            [ActionName("getUserById")]
            [EnableCors(origins: "*", headers: "*", methods: "*")]
            [System.Web.Http.HttpPost]
            public User getUserById([FromBody]User objUser)
            {
                User list = new User();
                list = Db.getUserById(Convert.ToInt32(objUser.Id));
                return list;
            }
    
            [Authorize]
            [ActionName("keyStatus")]
            [EnableCors(origins: "*", headers: "*", methods: "*")]
            [System.Web.Http.HttpPost]
            public string keyStatus()
            {
               return "Ok";
            }
        }
    }
    

    Step-6. Change your ApplicationOAuthProvider.cs file like this


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.Cookies;
    using Microsoft.Owin.Security.OAuth;
    using API_OwinDemo.Models;
    using API.Models;
    
    namespace API_OwinDemo.Providers
    {
        public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
        {
            private readonly string _publicClientId;
    
            public ApplicationOAuthProvider(string publicClientId)
            {
                if (publicClientId == null)
                {
                    throw new ArgumentNullException("publicClientId");
                }
    
                _publicClientId = publicClientId;
            }
    
            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                //var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
    
                //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
    
                //if (user == null)
                //{
                //    context.SetError("invalid_grant", "The user name or password is incorrect.");
                //    return;
                //}
    
                //ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                //   OAuthDefaults.AuthenticationType);
                //ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                //    CookieAuthenticationDefaults.AuthenticationType);
    
                //AuthenticationProperties properties = CreateProperties(user.UserName);
                //AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                //context.Validated(ticket);
                //context.Request.Context.Authentication.SignIn(cookiesIdentity);
    
                bool isValidUser = false;
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
    
                if (context.UserName == "test" && context.Password == "test")
                {
                    isValidUser = true;
                }
                User list = new User();
                AppDataConetext Db = new AppDataConetext();
                list = Db.validateUser(context.UserName, context.Password);
                if (list != null)
                {
                    isValidUser = true;
                }
    
                if (!isValidUser)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
    
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));
                identity.AddClaim(new Claim("role", "user"));
    
                context.Validated(identity);
            }
    
            public override Task TokenEndpoint(OAuthTokenEndpointContext context)
            {
                foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
                {
                    context.AdditionalResponseParameters.Add(property.Key, property.Value);
                }
    
                return Task.FromResult<object>(null);
            }
    
            public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
            {
                // Resource owner password credentials does not provide a client ID.
                if (context.ClientId == null)
                {
                    context.Validated();
                }
    
                return Task.FromResult<object>(null);
            }
    
            public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
            {
                if (context.ClientId == _publicClientId)
                {
                    Uri expectedRootUri = new Uri(context.Request.Uri, "/");
    
                    if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                    {
                        context.Validated();
                    }
                }
    
                return Task.FromResult<object>(null);
            }
    
            public static AuthenticationProperties CreateProperties(string userName)
            {
                IDictionary<string, string> data = new Dictionary<string, string>
                {
                    { "userName", userName }
                };
                return new AuthenticationProperties(data);
            }
        }
    }
    

    Step-7. Update Your WebApiConfig.cs file like this


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Web.Http;
    using Microsoft.Owin.Security.OAuth;
    using Newtonsoft.Json.Serialization;
    using System.Web.Http.Cors;
    
    namespace API_OwinDemo
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                //// Web API configuration and services
                //// Configure Web API to use only bearer token authentication.
                //config.SuppressDefaultHostAuthentication();
                //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    
                //// Web API routes
                //config.MapHttpAttributeRoutes();
    
                var cors = new EnableCorsAttribute("*", "*", "*");
                config.EnableCors();
    
                config.Routes.MapHttpRoute(
                    name: "WithActionApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                     defaults: new { id = RouteParameter.Optional }
                );
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }
    
    Finaly you have creted and Done with API project now create 1 html page to test your OWIN Token Based Authentication

    Step-8. Add html page to test your OWIN Token Based Authentication

    Your Html page like this
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>owin authentication web api example, Token Based Authentication Using ASP.Net Web API with Ajax, OWIN  </title>
        <link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
        <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>
        <link href="Content/css/style.css" rel="stylesheet" />
        <link href="Content/css/jquery-ui.css" rel="stylesheet" />
        <script src="Content/js/jquery-1.12.4.js"></script>
        <script src="Content/js/jquery-ui.js"></script>
    </head>
    <body>
        <div class="pen-title">
            <h1> owin authentication web api example, Token Based Authentication Using ASP.Net Web API with Ajax</h1>
        </div>
        <div class="module form-module">
            <div class="form">
                <h2>owin authentication web api example Log in and validate user</h2>
                <form>
                    <input type="text" placeholder="Username" id="loginUserName" />
                    <input type="password" placeholder="Password" id="loginPassword" />
                    <button onclick="validateUser(); return false">Login</button>
                </form>
            </div>
        </div>
        <!--<script src="Content/js/jquery.min.js"></script>-->
        <script src="Content/js/index.js"></script>
        <style>
            .at-button {
            }
        </style>
        <script>
            var type = "local";
            var rootUrl = "";
    
                //Start - this is for testing only
                if (type == "local") {
                    rootUrl = "http://localhost:15489/";
                }
                else if (type == "iis") {
                    rootUrl = "http://192.168.0.179:81/";
                }
                else if (type == "sandbox") {
                    rootUrl = "";
                }
                else if (type == "live") {
                    rootUrl = "";
                }
                //End
    
            $('#loginUserName #loginPassword').keyup(function (e) {
                if (e.keyCode == 13) {
                    validateUser();
                }
            });
    
            function validateUser() {
                if ($("#loginUserName").val() == "" || $("#loginPassword").val() == "") {
                    alert('Please enter username or password');
                    return false;
                }
    
                jQuery.support.cors = true;  
    
                $.ajax({
                    url: rootUrl + "TOKEN",
                    crossDomain: true,
                    method: "POST",
                    dataType: "json",
                    data: $.param({ grant_type: 'password', username: $('#loginUserName').val(), password: $('#loginPassword').val() }),
                    //contentType: "application/json;",
                    //headers: { 'Content-Type': 'application/x-www-form-urlencoded', "X-Custom-Header": "*" },
                    //headers: {  'X-Custom-Header' },
                    //headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': '*' },
                    //headers: {'Content-Type': 'Access-Control-Request-Headers','X-Custom-Header','application/x-www-form-urlencoded', "X-Custom-Header": "33" },
                    //headers: { "X-Octopus-ApiKey": "API-xxxxxxxxx" },
                    success: function (data) {
                        if (data != null) {
                            localStorage.setItem('accessToken', data.access_token);
                        }
                        else if (data.error_description != null)
                        {
                            alert(data.error_description);
                        }
                        else {
                            alert('Username or password is wrong');
                        }
                    },
                    error: function (jqxhr) {
                        alert('Username or password is wrong');
                    }
                });
                return false;
            }
            function getUserById(Id) {
                var headers = {};
                headers = getHeaders();
                var UserData =
                {
                    Id: Id
                };
                $.ajax({
                    type: "POST",
                    crossDomain: true,
                    data: JSON.stringify(UserData),
                    url: rootUrl + "api/WebAPI/getUserById",
                    dataType: "json",
                    contentType: "application/json",
                    headers: headers,
                    success: function (data) {
                        $('#UserName').val(data.UserName);
                        $('#Password').val(data.Password);
                    },
                    error: function (jqXHR, status, text) {
                        keyIsExpired(jqXHR, status, text);
                    }
                });
            }
            function openRegister() {
                $('#btnRegister').click();
            }
            function keyIsExpired(jqXHR, status, text) {
                localStorage.setItem('accessToken', '');
                if (jqXHR.status == 500) {
                    // Server side error
                } else if (jqXHR.status == 302 || jqXHR.status == 404 || jqXHR.status == 401) {
                    alert('Authantication key is expired, required login to continue...');
                    window.location.href = "login.html";
                }
            }
            function getHeaders() {
                var token = localStorage.getItem('accessToken');
                var headers = {};
                if (token) {
                    headers.Authorization = 'Bearer ' + token;
                }
                if (token == null || token == "") {
                    window.location.href = "loginRegister.html";
                }
                return headers;
            }
            function getParameterByName(name, url) {
                if (!url) {
                    url = window.location.href;
                }
                name = name.replace(/[\[\]]/g, "\\$&");
                var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                    results = regex.exec(url);
                if (!results) return null;
                if (!results[2]) return '';
                return decodeURIComponent(results[2].replace(/\+/g, " "));
            }
    
            $(document).ready(function () {
                var Id = getParameterByName('id');
                if (Id != null && Id != "") {
                    var token = localStorage.getItem('accessToken');
                    if (token == null || token == "")
                    {
                        window.location.href = "loginRegister.html";
                    }
                    else
                    {
                        //keyStatus();
                        getUserById(Id);
                        $('#Password').hide();
                        $('#Id').val(Id);
                        $("#btnRegisterUpdate").html('Update');
                    }
                }
            });
        </script>
    </body>
    </html>
    
    Now You are complete done with Token Based Authentication OWIN example, first build the webApi project and run it. and then run html page and login.

    Friday 24 March 2017

    export datatable to excel c#



    All about in export functionality using OpenXML and ClosedXML
    You can export your datatable to xls or xlsx easy.
    export datatable to excel in asp.net
    export datatable to excel in MVC
    export datatable to .xlsx format using c#
    Export DataTable to Excel with Formatting in C#
    Export a DataTable to an Excel file and add format to the contents while writing the Excel file.
    this example export all columns or you can be set remove columns to export


    use like this:


    ExportDt2Excel("Report", XLColor.White, XLColor.Black, 20, false, "01/06/2017", "01/07/2017", XLColor.White,
                                   XLColor.Black, 10, tbl, XLColor.Orange, XLColor.White, "report",
                                   "MyData.xlsx","","");
    

    Example:

    public string ExportDt2Excel(string Title, XLColor HeaderBackgroundColor, XLColor HeaderForeColor, int HeaderFont,
    
                    bool DateRange, string FromDate, string ToDate, XLColor DateRangeBackgroundColor,
                    XLColor DateRangeForeColor, int DateRangeFont, DataTable gv, XLColor ColumnBackgroundColor,
                    XLColor ColumnForeColor, string SheetName, string FileName,string RemoveDtColumnsByName, string RemoveCoulmnsByIndex)
        {
        DataTable table = gv;
        if (!string.IsNullOrEmpty(RemoveDtColumnsByName))
        {
        foreach (var item in RemoveDtColumnsByName.Split(','))
        {
            table.Columns.Remove(item);
        }
        }
        if (gv != null)
        {
        var wb = new XLWorkbook();
        var ws = wb.Worksheets.Add(SheetName);
        ws.Cell("A1").Value = Title;
        if (DateRange)
        {
            ws.Cell("A2").Value = "Date Range :" + FromDate + " - " + ToDate;
        }
        else
        {
            ws.Cell("A2").Value = "";
        }
    
        //add columns
        string[] cols = new string[table.Columns.Count];
        for (int c = 0; c < table.Columns.Count; c++)
        {
            var a = table.Columns[c].ToString();
            cols[c] = table.Columns[c].ToString().Replace('_', ' ');
        }
    
    
        char StartCharCols = 'A';
        int StartIndexCols = 3;
        for (int i = 1; i <= cols.Length; i++)
        {
            if (i == cols.Length)
            {
                string DataCell = StartCharCols.ToString() + StartIndexCols.ToString();
                ws.Cell(DataCell).Value = cols[i - 1];
                ws.Cell(DataCell).WorksheetColumn().Width = cols[i - 1].ToString().Length + 10;
                ws.Cell(DataCell).Style.Font.Bold = true;
                ws.Cell(DataCell).Style.Fill.BackgroundColor = ColumnBackgroundColor;
                ws.Cell(DataCell).Style.Font.FontColor = ColumnForeColor;
            }
            else
            {
                string DataCell = StartCharCols.ToString() + StartIndexCols.ToString();
                ws.Cell(DataCell).Value = cols[i - 1];
                ws.Cell(DataCell).WorksheetColumn().Width = cols[i - 1].ToString().Length + 10;
                ws.Cell(DataCell).Style.Font.Bold = true;
                ws.Cell(DataCell).Style.Fill.BackgroundColor = ColumnBackgroundColor;
                ws.Cell(DataCell).Style.Font.FontColor = ColumnForeColor;
                StartCharCols++;
            }
        }
        //Merging Header
    
        string Range = "A1:" + StartCharCols.ToString() + "1";
    
        ws.Range(Range).Merge();
        ws.Range(Range).Style.Font.FontSize = HeaderFont;
        ws.Range(Range).Style.Font.Bold = true;
    
        ws.Range(Range).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Center);
        ws.Range(Range).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
        if (HeaderBackgroundColor != null && HeaderForeColor != null)
        {
            ws.Range(Range).Style.Fill.BackgroundColor = HeaderBackgroundColor;
            ws.Range(Range).Style.Font.FontColor = HeaderForeColor;
        }
    
        //Style definitions for Date range
        Range = "A2:" + StartCharCols.ToString() + "2";
    
        ws.Range(Range).Merge();
        ws.Range(Range).Style.Font.FontSize = 10;
        ws.Range(Range).Style.Font.Bold = true;
        ws.Range(Range).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Bottom);
        ws.Range(Range).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Right);
    
        //border definitions for Columns
        Range = "A3:" + StartCharCols.ToString() + "3";
        ws.Range(Range).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        ws.Range(Range).Style.Border.RightBorder = XLBorderStyleValues.Thin;
        ws.Range(Range).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        ws.Range(Range).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
    
        char StartCharData = 'A';
        int StartIndexData = 4;
    
        char StartCharDataCol = char.MinValue;
        for (int i = 0; i < table.Rows.Count; i++)
        {
            for (int j = 0; j < table.Columns.Count ; j++)
            {
    
                string DataCell = StartCharData.ToString() + StartIndexData;
                var a = table.Rows[i][j].ToString();
                a = a.Replace("&nbsp;", " ");
                a = a.Replace("&amp;", "&");
                //check if value is of integer type
                int val = 0;
                DateTime dt = DateTime.Now;
                if (int.TryParse(a, out val))
                {
                    ws.Cell(DataCell).Value = val;
                }
                else if (DateTime.TryParse(a, out dt))
                {
                    ws.Cell(DataCell).Value = dt.ToShortDateString();
                }
                ws.Cell(DataCell).SetValue(a);
                StartCharData++;
            }
            StartCharData = 'A';
            StartIndexData++;
        }
        //Code to save the file
        using (MemoryStream memoryStream = new MemoryStream())
        {
            wb.SaveAs(memoryStream);
            string saveAsFileName = string.Format("PurchaseReport-{0:d}.xlsx", DateTime.Now).Replace("/", "-");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
            Response.Clear();
            memoryStream.WriteTo(memoryStream);
            memoryStream.Close();
            Response.BinaryWrite(memoryStream.GetBuffer());
            Response.End();
        }
        return "Done";
        }
        else
        {
        return "DataTable is null";
        }
    
    
        }
        }
    


    Asp.net tutorials