Skip to content

Commit

Permalink
Added a .NET Core SampleWebApp
Browse files Browse the repository at this point in the history
  • Loading branch information
VahidN committed Feb 9, 2018
1 parent 2d08514 commit 72be3ce
Show file tree
Hide file tree
Showing 14 changed files with 351 additions and 0 deletions.
216 changes: 216 additions & 0 deletions SampleWebApp.Core/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
using System;
using System.Data;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;
using OfficeOpenXml.Table;

namespace SampleWebApp.Core.Controllers
{
public class HomeController : Controller
{
private const string XlsxContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
private readonly IHostingEnvironment _hostingEnvironment;

public HomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}

/// <summary>
/// /Home/FileReport
/// </summary>
public IActionResult FileReport()
{
var fileDownloadName = "report.xlsx";
var reportsFolder = "reports";

using (var package = createExcelPackage())
{
package.SaveAs(new FileInfo(Path.Combine(_hostingEnvironment.WebRootPath, reportsFolder, fileDownloadName)));
}
return File($"~/{reportsFolder}/{fileDownloadName}", XlsxContentType, fileDownloadName);
}

public IActionResult Index()
{
return View();
}

/// <summary>
/// An in-memory report
/// </summary>
public IActionResult InMemoryReport()
{
byte[] reportBytes;
using (var package = createExcelPackage())
{
reportBytes = package.GetAsByteArray();
}

return File(reportBytes, XlsxContentType, "report.xlsx");
}

/// <summary>
/// /Home/ReadFile
/// </summary>
public IActionResult ReadFile()
{
var fileDownloadName = "report.xlsx";
var reportsFolder = "reports";
var fileInfo = new FileInfo(Path.Combine(_hostingEnvironment.WebRootPath, reportsFolder, fileDownloadName));
if (!fileInfo.Exists)
{
using (var package = createExcelPackage())
{
package.SaveAs(fileInfo);
}
}

return Content(readExcelPackage(fileInfo, worksheetName: "Employee"));
}

public async Task<IActionResult> FileUpload(IFormFile file)
{
if (file == null || file.Length == 0)
{
return RedirectToAction("Index");
}

using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream).ConfigureAwait(false);

using (var package = new ExcelPackage(memoryStream))
{
var worksheet = package.Workbook.Worksheets[1]; // Tip: To access the first worksheet, try index 1, not 0
return Content(readExcelPackageToString(package, worksheet));
}
}
}

/// <summary>
/// /Home/DataTableReport
/// </summary>
public IActionResult DataTableReport()
{
var dataTable = new DataTable("Users");
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Age", typeof(int));
var rnd = new Random();
for (var i = 0; i < 100; i++)
{
var row = dataTable.NewRow();
row["Name"] = $"User {i}";
row["Age"] = rnd.Next(20, 100);
dataTable.Rows.Add(row);
}

using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("Excel Test");
worksheet.Cells["A1"].LoadFromDataTable(dataTable, PrintHeaders: true);
for (var col = 1; col < dataTable.Columns.Count + 1; col++)
{
worksheet.Column(col).AutoFit();
}
return File(package.GetAsByteArray(), XlsxContentType, "report.xlsx");
}
}

private string readExcelPackage(FileInfo fileInfo, string worksheetName)
{
using (var package = new ExcelPackage(fileInfo))
{
return readExcelPackageToString(package, package.Workbook.Worksheets[worksheetName]);
}
}

private string readExcelPackageToString(ExcelPackage package, ExcelWorksheet worksheet)
{
var rowCount = worksheet.Dimension?.Rows;
var colCount = worksheet.Dimension?.Columns;

if (!rowCount.HasValue || !colCount.HasValue)
{
return string.Empty;
}

var sb = new StringBuilder();
for (int row = 1; row <= rowCount.Value; row++)
{
for (int col = 1; col <= colCount.Value; col++)
{
sb.AppendFormat("{0}\t", worksheet.Cells[row, col].Value);
}
sb.Append(Environment.NewLine);
}
return sb.ToString();
}

private ExcelPackage createExcelPackage()
{
var package = new ExcelPackage();
package.Workbook.Properties.Title = "Salary Report";
package.Workbook.Properties.Author = "Vahid N.";
package.Workbook.Properties.Subject = "Salary Report";
package.Workbook.Properties.Keywords = "Salary";


var worksheet = package.Workbook.Worksheets.Add("Employee");

//First add the headers
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
worksheet.Cells[1, 3].Value = "Gender";
worksheet.Cells[1, 4].Value = "Salary (in $)";

//Add values

var numberformat = "#,##0";
var dataCellStyleName = "TableNumber";
var numStyle = package.Workbook.Styles.CreateNamedStyle(dataCellStyleName);
numStyle.Style.Numberformat.Format = numberformat;

worksheet.Cells[2, 1].Value = 1000;
worksheet.Cells[2, 2].Value = "Jon";
worksheet.Cells[2, 3].Value = "M";
worksheet.Cells[2, 4].Value = 5000;
worksheet.Cells[2, 4].Style.Numberformat.Format = numberformat;

worksheet.Cells[3, 1].Value = 1001;
worksheet.Cells[3, 2].Value = "Graham";
worksheet.Cells[3, 3].Value = "M";
worksheet.Cells[3, 4].Value = 10000;
worksheet.Cells[3, 4].Style.Numberformat.Format = numberformat;

worksheet.Cells[4, 1].Value = 1002;
worksheet.Cells[4, 2].Value = "Jenny";
worksheet.Cells[4, 3].Value = "F";
worksheet.Cells[4, 4].Value = 5000;
worksheet.Cells[4, 4].Style.Numberformat.Format = numberformat;

// Add to table / Add summary row
var tbl = worksheet.Tables.Add(new ExcelAddressBase(fromRow: 1, fromCol: 1, toRow: 4, toColumn: 4), "Data");
tbl.ShowHeader = true;
tbl.TableStyle = TableStyles.Dark9;
tbl.ShowTotal = true;
tbl.Columns[3].DataCellStyleName = dataCellStyleName;
tbl.Columns[3].TotalsRowFunction = RowFunctions.Sum;
worksheet.Cells[5, 4].Style.Numberformat.Format = numberformat;

// AutoFitColumns
worksheet.Cells[1, 1, 4, 4].AutoFitColumns();

worksheet.HeaderFooter.OddFooter.InsertPicture(
new FileInfo(Path.Combine(_hostingEnvironment.WebRootPath, "images", "captcha.jpg")),
PictureAlignment.Right);

return package;
}
}
}
20 changes: 20 additions & 0 deletions SampleWebApp.Core/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System.IO;
using Microsoft.AspNetCore.Hosting;

namespace SampleWebApp.Core
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();

host.Run();
}
}
}
27 changes: 27 additions & 0 deletions SampleWebApp.Core/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:2463/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"EPPlus.Core.SampleWebApp": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:5000"
}
}
}
17 changes: 17 additions & 0 deletions SampleWebApp.Core/SampleWebApp.Core.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EPPlus\EPPlus.MultiTarget.csproj" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
</ItemGroup>
</Project>
22 changes: 22 additions & 0 deletions SampleWebApp.Core/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace SampleWebApp.Core
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseMvcWithDefaultRoute();
app.UseDefaultFiles();
app.UseStaticFiles();
}
}
}
28 changes: 28 additions & 0 deletions SampleWebApp.Core/Views/Home/Index.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<fieldset>
<legend>Basic usage</legend>
<ul>
<li>
<a asp-action="InMemoryReport" asp-controller="Home">Create an in-memory report</a>
</li>
<li>
<a asp-action="FileReport" asp-controller="Home">Create a file report</a>
</li>
<li>
<a asp-action="DataTableReport" asp-controller="Home">Create a DataTable report</a>
</li>
<li>
<a asp-action="ReadFile" asp-controller="Home">Read report.xlsx file</a>
</li>
</ul>
</fieldset>

<fieldset style="margin-top: 15px">
<legend>Upload an xlsx file</legend>
<form method="post"
asp-action="FileUpload"
asp-controller="Home"
enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
</fieldset>
14 changes: 14 additions & 0 deletions SampleWebApp.Core/Views/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>EPPlus.Core.SampleWebApp</title>
</head>
<body>
<div >
@RenderBody()
</div>
@RenderSection("Scripts", required: false)
</body>
</html>
1 change: 1 addition & 0 deletions SampleWebApp.Core/Views/_ViewImports.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
3 changes: 3 additions & 0 deletions SampleWebApp.Core/Views/_ViewStart.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}
2 changes: 2 additions & 0 deletions SampleWebApp.Core/_0-restore.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dotnet restore
pause
1 change: 1 addition & 0 deletions SampleWebApp.Core/_1_dotnet_run.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dotnet watch run
Binary file added SampleWebApp.Core/wwwroot/images/captcha.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Binary file added SampleWebApp.Core/wwwroot/reports/report.xlsx
Binary file not shown.

0 comments on commit 72be3ce

Please sign in to comment.