Press Me
How to attach EPPlus Library
- PM>Install-Package EPPlus
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BAL;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
using System.Drawing;
using System.Data;
using System.Reflection;
using OfficeOpenXml;
using System.Text;
using OfficeOpenXml.Style;
namespace APIToExcel.Controllers
{
public class WebApiToExcelController : Controller
{
// GET: WebApiToExcel
public ActionResult Index()
{
List<PMGECODetailDto> lst = new List<PMGECODetailDto>();
DataTable dt = new DataTable();
try
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var url = "https://mercurydev.glb.itcs.hpecorp.net/EncoreNGAPI/api/pmgECOmaterialBOM/GetECOBydate?currentdate=" + DateTime.UtcNow.Month + "/" + DateTime.UtcNow.Day + "/" + DateTime.UtcNow.Year;
HttpResponseMessage response = httpClient.GetAsync(url).Result;
lst = JsonConvert.DeserializeObject<List<PMGECODetailDto>>(response.Content.ReadAsStringAsync().Result);
dt = ConvertlistToDatatable(lst);
}
using (var xlPackage = new ExcelPackage())
{
var workSheet = xlPackage.Workbook.Worksheets.Add(DateTime.UtcNow.Month+"-"+DateTime.UtcNow.Day+"-"+DateTime.UtcNow.Year);
workSheet.Cells["A1"].LoadFromDataTable(dt, true);
workSheet.Cells.Style.Font.Size = 11;
workSheet.Cells[1, 1, 1, dt.Columns.Count].AutoFilter = true;
workSheet.Cells.AutoFitColumns(0);
using (var range = workSheet.Cells[1, 1, 1, dt.Columns.Count])
{
range.Style.Font.Bold = true;
range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
range.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);
range.Style.Font.Color.SetColor(Color.White);
}
dt.Dispose();
FileInfo fi = new FileInfo(Server.MapPath("~/ApiToExcell/"+ DateTime.UtcNow.Month + "-" + DateTime.UtcNow.Day + "-" + DateTime.UtcNow.Year+".xlsx"));
xlPackage.SaveAs(fi);
}
}
catch (Exception ex)
{
throw ex;
}
return View(lst);
}
public DataTable ConvertlistToDatatable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
}
}
No comments:
Post a Comment