Here in this tutorial I will teach you how to export your Database Records into Excel file using 2 different methods. You can choose any one of these methods when doing your data export to excel file.
In this method the DataSet is filled with Records from the Database. Then I loop through these records in the DataSet’s table and convert them to an HTML table. Finally the HTML table is wrote into an excel file.
Add the following code to the Index View:
@using (Html.BeginForm("Index", "ExportExcel"))
{
<button id="submitButton" type="submit">Create Simple Excel</button>
}
In the Controller add the below code:
[HttpPost]
[ActionName("Index")]
public ActionResult Index_Post()
{
//Fill dataset with records
DataSet dataSet = GetRecordsFromDatabase();
StringBuilder sb = new StringBuilder();
sb.Append("<table>");
//LINQ to get Column names
var columnName = dataSet.Tables[0].Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
sb.Append("<tr>");
//Looping through the column names
foreach (var col in columnName)
sb.Append("<td>" + col + "</td>");
sb.Append("</tr>");
//Looping through the records
foreach (DataRow dr in dataSet.Tables[0].Rows)
{
sb.Append("<tr>");
foreach (DataColumn dc in dataSet.Tables[0].Columns)
{
sb.Append("<td>" + dr[dc] + "</td>");
}
sb.Append("</tr>");
}
sb.Append("</table>");
//Writing StringBuilder content to an excel file.
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=UserReport.xls");
Response.Write(sb.ToString());
Response.Flush();
Response.Close();
return View();
}
DataSet GetRecordsFromDatabase()
{
DataSet dataSet = new DataSet();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * FROM Sale";
cmd.Connection = conn;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = cmd;
sqlDataAdapter.Fill(dataSet);
return dataSet;
}
Explanation:
When the HTML table is created I write the StringBuilder object’s content (which is an HTML Table) into an excel file, and in this way I accomplish my Export to Excel procedure
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=UserReport.xls");
Response.Write(sb.ToString());
When writing the content to an excel file, you need to put Response.ContentType as application/vnd.ms-excel, and pass content-disposition”, “attachment;filename=UserReport.xls for the parameter of Response.AddHeader function.
Finally using the Response.Write() function I write the content to the excel file.
This is the simplest and fastest method to accomplish the Export to Excel task in ASP.NET MVC.
In this method you have to add Microsoft.Office.Interop.Excel DLL to your project. This DLL is available from NuGet.
In the view add the below code:
@using (Html.BeginForm("Interop", "ExportExcel"))
{
<button id="interOpButton" type="submit">Create Microsoft Office Interop Excel</button>
}
In the controller you add the namespace using Microsoft.Office.Interop.Excel; and then create an Interop Action which has the code given below:
[HttpPost]
public ActionResult Interop()
{
DataSet dataSet = GetRecordsFromDatabase();
//Creating Object of Microsoft.Office.Interop.Excel and creating a Workbook
var excelApp = new Application();
excelApp.Visible = true;
excelApp.Workbooks.Add();
Worksheet workSheet = (Worksheet)excelApp.ActiveSheet; //creating excel worksheet
workSheet.Name = "Sale"; //name of excel file
//LINQ to get Column of dataset table
var columnName = dataSet.Tables[0].Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
int i = 0;
//Adding column name to worksheet
foreach (var col in columnName)
{
i++;
workSheet.Cells[1, i] = col;
}
//Adding records to worksheet
int j;
for (i = 0; i < dataSet.Tables[0].Rows.Count; i++)
{
for (j = 0; j < dataSet.Tables[0].Columns.Count; j++)
{
workSheet.Cells[i + 2, j+1] = Convert.ToString(dataSet.Tables[0].Rows[i][j]);
}
}
//Saving the excel file to “e” directory
workSheet.SaveAs("e:\\" + workSheet.Name);
return RedirectToAction("Index");
}
Explanation
In this way I did the Export to Excel of my records using the DLL method.
Conclusion
I provided the 2 methods to Export your data to an Excel File in ASP.NET method. Both these methods are extremely useful and will help you in your project development.