ASP.NET 4.6 Hosting Tutorial – How to Read & Show Excel Files in ASP.NET

Microsoft Office Excel is a spreadsheet-application which a good mean to store data in spreadsheet in a table (tabular) form. In this article, we will see how to display data (retrive data or read data) from an Excel spreadsheet using ASP.NET.

excel-round-function

We are going to read an Excel file in ASP.NET. Our ASP page will be on remote server and an Excel file in our desktop. First of all we need to upload it to a remote server and then retrive the data. So we are design a form to upload an excel. There will be possibility that we have to retrive data from a file again and again so we will rename Excel and then upload it.

<%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default.aspx.vb” Inherits=”_Default” %>
<!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>Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET</title>
<style type=”text/css”>
tr.sectiontableentry1 td,
tr.sectiontableentry2 td {
padding: 4px;
}
tr.sectiontableentry1 td {
padding: 8px 5px;
background: url(hline.gif) repeat-x bottom;
}
tr.sectiontableentry2 td {
padding: 8px 5px;
background: url(hline.gif) repeat-x bottom #F2F2F2;
}
</style>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<table style=”padding: 5px; font-size: 11px;” align=”center” border=”0″>
<tbody>
<tr>
<td>
<strong>Please Select Excel file containing job details…</strong>
</td>
</tr>
<tr>
<td>
<div style=”background: url(hline.gif) repeat-x bottom #F2F2F2;padding: 8px 5px;border-bottom: 1px solid #ccc;”>
<asp:FileUpload ID=”txtFilePath” runat=”server”></asp:FileUpload>&nbsp;&nbsp;
<asp:Button ID=”btnUpload” runat=”server” Text=”Upload” /><br />
<asp:Label ID=”lblMessage” runat=”server” Visible=”False” Font-Bold=”True”
ForeColor=”#009933″></asp:Label>
</div>
</td>
</tr>
<tr>
<td>
<asp:GridView ID=”grvExcelData” runat=”server”>
<RowStyle CssClass=”sectiontableentry2″ />
<AlternatingRowStyle CssClass=”sectiontableentry1″ />
</asp:GridView>
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
</html>

Connection to Excel with Microsoft OLE DB Provider for Jet

The Microsoft OLE DB Provider for Jet(stands for Joint Engine Technology is a database engine) provides an OLE DB interface to Microsoft Access databases, and allows SQL Server 2005 and later distributed queries to query Access databases and Excel spreadsheets. We will connect to a Microsoft Excel workbook using the Microsoft OLE DB Provider for Jet 4.0, read data and then display the data in a GridView.

xlsx (Excel 2007) contains Microsoft.ACE.OLEDB.12.0 as the provider. This is the new Access database engine OLE DB driver and is also capable of reading Excel 2003. We are going to use it to read xlsx (Excel 2007) data.

We have a excel file whose content are as shown below. Note here sheet name must be same, means if want to read data from Sheet1. You must take care while writting SQL query because SELECT * FROM [Sheet1$] and SELECT * FROM [sheet1$] are two different queries.

Excelldata

VB.NET Code

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
If (txtFilePath.HasFile) Then
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim query As String
Dim connString As String = “”
Dim strFileName As String = DateTime.Now.ToString(“ddMMyyyy_HHmmss”)
Dim strFileType As String = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower()

‘Check file type
If strFileType.Trim = “.xls” Or strFileType.Trim = “.xlsx” Then
txtFilePath.SaveAs(Server.MapPath(“~/UploadedExcel/” & strFileName & strFileType))
Else
lblMessage.Text = “Only excel files allowed”
lblMessage.ForeColor = Drawing.Color.Red
lblMessage.Visible = True
Exit Sub
End If

Dim strNewPath As String = Server.MapPath(“~/UploadedExcel/” & strFileName & strFileType)

‘Connection String to Excel Workbook
If strFileType.Trim = “.xls” Then
connString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & strNewPath & “;Extended Properties=””Excel 8.0;HDR=Yes;IMEX=2″””
ElseIf strFileType.Trim = “.xlsx” Then
connString = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=” & strNewPath & “;Extended Properties=””Excel 12.0;HDR=Yes;IMEX=2″””
End If

query = “SELECT * FROM [Sheet1$]”

‘Create the connection object
conn = New OleDbConnection(connString)
‘Open connection
If conn.State = ConnectionState.Closed Then conn.Open()
‘Create the command object
cmd = New OleDbCommand(query, conn)
da = New OleDbDataAdapter(cmd)
ds = New DataSet()
da.Fill(ds)

grvExcelData.DataSource = ds.Tables(0)
grvExcelData.DataBind()

da.Dispose()
conn.Close()
conn.Dispose()
Else
lblMessage.Text = “Please select an excel file first”
lblMessage.ForeColor = Drawing.Color.Red
lblMessage.Visible = True
End If
End Sub

C#.NET Code

protected void btnUpload_Click(object sender, EventArgs e)
{
if ((txtFilePath.HasFile))
{

OleDbConnection conn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string query = null;
string connString = “”;
string strFileName = DateTime.Now.ToString(“ddMMyyyy_HHmmss”);
string strFileType = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower();

//Check file type
if (strFileType == “.xls” || strFileType == “.xlsx”)
{
txtFilePath.SaveAs(Server.MapPath(“~/UploadedExcel/” + strFileName + strFileType));
}
else
{
lblMessage.Text = “Only excel files allowed”;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Visible = true;
return;
}

string strNewPath = Server.MapPath(“~/UploadedExcel/” + strFileName + strFileType);

//Connection String to Excel Workbook
if (strFileType.Trim() == “.xls”)
{
connString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + strNewPath + “;Extended Properties=\”Excel 8.0;HDR=Yes;IMEX=2\””;
}
else if (strFileType.Trim() == “.xlsx”)
{
connString = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=” + strNewPath + “;Extended Properties=\”Excel 12.0;HDR=Yes;IMEX=2\””;
}

query = “SELECT * FROM [Sheet1$]”;
//query = “SELECT [Country],[Capital] FROM [Sheet1$] WHERE [Currency]=’Rupee’”
//query = “SELECT [Country],[Capital] FROM [Sheet1$]”

//Create the connection object
conn = new OleDbConnection(connString);
//Open connection
if (conn.State == ConnectionState.Closed) conn.Open();
//Create the command object
cmd = new OleDbCommand(query, conn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);

grvExcelData.DataSource = ds.Tables[0];
grvExcelData.DataBind();

lblMessage.Text = “Data retrieved successfully! Total Records:” + ds.Tables[0].Rows.Count;
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Visible = true;

da.Dispose();
conn.Close();
conn.Dispose();
}
else
{
lblMessage.Text = “Please select an excel file first”;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Visible = true;
}
}

We have tested above code and got result as shown below:

Retrieved_Excel_data


ASP.NET 4.6 Hosting with HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. They deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. They have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

awards-03.pngHostForLIFE.eu is Microsoft No #1 Recommended Windows and ASP.NET Hosting in European Continent. Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and many top European countries.

HostForLIFE.eu Hosting is the first host to offer its customer all the new features of the ASP.NET 4.6 Hosting. You can simply deploy your ASP.NET 4.6 website via our world-class Control Panel or conventional FTP tool. This ASP.NET 4.6 Hosting is part of HostForLIFE.eu service and it is provided free of charge.

ASP.NET Core 1.0 Hosting Tutorial – How To Find & Use Session in ASP.NET Core 1.0

If you’re just starting to develop in ASP.NET, you may not have encountered Session before. Session is a serialized collection of objects that are related to the current user’s session. The values are usually stored on the local server memory, but there are alternate architectures where the values can be stored in a SQL database or other distributed storage solutions, especially when your servers are part of a server farm. In this tutorial, we will show you how to find and use session in ASP.NET Core 1.0.flat-vector-design-illustration-of-modern-business-office-and-workspace-600x500

Finding Session in ASP.NET Core 1.0

ASP.NET Core 1.0 has been written from the ground up to be a modular, choose-what-you-need framework. What this means is that you must explicitly include any packages you want to use in your project. This allows developers to maintain tight control over what functionality our ASP.NET Core projects actually need, and exclude anything that is not necessary.

Step 1

Session is considered to be one of “additional” packages.  In order to include that package we need to add a reference to Microsoft.AspNet.Session in the project.json file. If we wanted to use memory as our caching backend, we would also include Microsoft.Extensions.Caching.Memory.

Finding Session in ASP.NET Core 1.0 (1)

Step 2

Once we’ve got the package included in our project, we need to make it available to the Services layer by modifying the ConfigureServices() method in the Startup file, like so:

Step 3

However, that isn’t quite enough to get Session fully integrated into our project. We also need to inject the Session service into our Dependency Injection container in the Startup file’s Configure() method, like so:

With all of these steps completed, you can now use Session in your projects just like in any other ASP.NET application. If you wanted to use a different cache backend (rather than memory) you could grab a different NuGet package like Redis or SqlServer. Don’t forget to check NuGet if you can’t find the functionality you need; it is probably there and you just need to download it.

Using Session in ASP.NET Core 1.0

ASP.NET Core 1.0 has introduced some new extension methods that we can use for accessing and storing Session values. The odd thing is that these extensions are not in Microsoft.AspNet.Session; rather, they are in Microsoft.AspNet.Http, and so we will need to add that package.

Using Session in ASP.NET Core 1.0 (1)

Once we’ve got that package included, we can start using the extension methods:

The new extension methods are:

  • Get: Returns a byte array for the specified Session object.
  • GetInt: Returns an integer value for the specified Session object.
  • GetString: Returns a string value for the specified Session object.
  • Set: Sets a byte array for the specified Session object.
  • SetInt: Sets an integer value for the specified Session object.
  • SetString: Sets a string value for the specified Session object.

Best and Recommended ASP.NET Core 1.0 Hosting

If you are looking at creating website of your own, hosting it with ASP.NET Core 1.0 can be a great choice. While there are various companies today who offer you ASP.NET Core 1.0 hosting services, it is extremely important for you to understand and compare the features that various companies offer. To make this search easier for you, we have listed down top 3 hosting providers which you need to compare for the best and recommended ASP.NET Core 1.0 hosting.

ASP.NET Hosting Tutorial – How To Run Common CheckBox Operations

  • In this post, we will explains how to run common operations (like check/uncheck checkboxes by value/text/index, min/max selection limit..etc) on ASP.NET CheckBoxList control using jQuery.

    How To Run Common CheckBox Operations in ASP.NET

    Step 1

    Let’s have following aspx code:

    Code on the server side:

    Rendered HTML code:

    Step 2

    How to get value of selected items:

    How To Run Common CheckBox Operations 1

     


    How to get index of selected items:

    It will display 0 based index of selected items. Suppose we select Item-1,Item-3,Item-4 then It’ll give output 0,2,3 in alert boxes.


    How to get text of selection items:

    As you’ve seen, Text is placed in label control(next of checkbox) in rendered HTML. So, $(this).next().html() is used to get text.

    How to check/uncheck all checkboxes:


    How to check items by index:

    uppose you have to check items by the given index.

    Similarly, you can uncheck items by setting “false” in prop.


    How to check items by value:

    In this Label text is compared and if text exists then corresponding checkbox is checked. The above code will select Item-1 and Item-3.


    How to max selection limit:

    The following code limits the number of checkboxes a user can select simultaneously:

    How To Run Common CheckBox Operations 2

    Similarly, you can implement Min Selection criteria.


    Best ASP.NET Hosting with HostForLIFE.eu

    HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. They deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. They have customers from around the globe, spread across every continent. They have served the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

    awards-03.pngHostForLIFE.eu is Microsoft No #1 Recommended Windows and ASP.NET Hosting in European Continent. Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and many top European countries.

    HostForLIFE.eu is the first host to offer its customer all the new features of the ASP.NET 4.6 hosting. You can simply deploy your ASP.NET 4.6 website via their world-class Control Panel or conventional FTP tool. This ASP.NET 4.6 hosting is part of HostForLIFE.eu service and it is provided free of charge.