Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
TS:
exportAsXLSXFromAPI(): void {
if (!!this.policyList && this.policyList.length !== 0) {
this.spinner.show();
this.policyListService
.downloadExcelFile(this.policyFilter).subscribe(data => {
if (!!data) {
const fileName = 'ARMS_PolicyList';
this.excelService.saveAsExcelFile(data, fileName);
}
},
(error) => {
// this.spinner.hide();
this.toastr.error(error, this.appMessages.message['common-error-
message'], {
timeOut: 3000,
positionClass: 'toast-bottom-right'
});
},
() => { this.spinner.hide(); }
);
}
}
SERVICE:
downloadExcelFile(policyFilter: PolicyFilterViewModel): Observable<any> {
return this._utilityService.getAttachmentFile(policyFilter,
'Policy/DownloadExcelFile');
}
utility.service.ts
getAttachmentFile(attachmentUrl: any, apiUrl: string): Observable<any> {
this.authToken = this.storage.get('token');
const subject = new ReplaySubject<Response>();
// Xhr creates new context so we need to create reference to this
const self = this;
let pending: boolean;
pending = true;
EXCEL.SERVICE.ts
@Injectable({
providedIn: 'root'
})
export class ExcelService {
constructor() { }
API
Controller
/// <summary>
/// The DownloadExcelFile
/// </summary>
/// <param name="policyFilterViewModel"></param>
/// <returns></returns>
[HttpPost]
public async Task<HttpResponseMessage>
DownloadExcelFile(PolicyFilterViewModel policyFilterViewModel)
{
if (!ModelState.IsValid)
{
return Request.CreateResponse(HttpStatusCode.BadRequest,
ModelErrors(ModelState));
}
var policyListResult = await
_policyProvider.GetExcelPolicies(policyFilterViewModel);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(policyListResult)
{
Headers =
{
ContentLength = policyListResult.Length,
ContentType = new MediaTypeHeaderValue("application/octet-
stream")
}
}
};
return result;
}
Provider:
/// <summary>
/// The GetExcelPolicies
/// </summary>
/// <param name="policyFilterViewModel">The policyFilterViewModel<see
cref="PolicyFilterViewModel"/></param>
/// <returns>The <see cref="List{PolicyExcelModel}"/></returns>
Task<byte[]> GetExcelPolicies(PolicyFilterViewModel policyFilterViewModel);
Service:
/// <summary>
/// The GetExcelPolicies
/// </summary>
/// <param name="policyFilterViewModel">The policyFilterViewModel<see
cref="PolicyFilterViewModel"/></param>
/// <returns>The <see cref="Task{List{PolicyDataModel}}"/></returns>
public async Task<byte[]> GetExcelPolicies(PolicyFilterViewModel
policyFilterViewModel)
{
policyFilterViewModel.PolicyBasedOnTransactionEffectiveDate =
Convert.ToInt32(ConfigCommonKeyReader.PolicyBasedOnTransactionEffectiveDate);
policyFilterViewModel.TopRecord =
Convert.ToInt32(ConfigCommonKeyReader.TopRecord);
policyFilterViewModel.IsExcel = true;
var policyListModel = await
_policyDataFactory.GetExcelPolicies(policyFilterViewModel);
return ExcelExportHelper.ExportExcel(policyListModel, "", false,
"ARMS_PolicyList", Constants.PolicyExcelHeader);
}
DataService
/// <summary>
/// The GetExcelPolicies
/// </summary>
/// <param name="policyFilterViewModel">The policyFilterViewModel<see
cref="PolicyFilterViewModel"/></param>
/// <returns>The <see cref="List{PolicyDataModel}"/></returns>
public async Task<List<PolicyDataModel>>
GetExcelPolicies(PolicyFilterViewModel policyFilterViewModel)
{
var result = await
_connectionFactory.GetSystemConnection.QueryAsync<PolicyDataModel>("[policy].
[GetPolicies]",
policyFilterViewModel, commandType: CommandType.StoredProcedure);
return result.ToList();
}
ExportExcelHelper.cs
namespace BusinessLayer.Core.Staging
{
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Linq;
/// <summary>
/// Defines the <see cref="ExcelExportHelper" />
/// </summary>
public static class ExcelExportHelper
{
/// <summary>
/// Gets the ExcelContentType
/// </summary>
public static string ExcelContentType => "application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet";
/// <summary>
/// The ListToDataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">The data<see cref="List{T}"/></param>
/// <returns>The <see cref="DataTable"/></returns>
private static DataTable ListToDataTable<T>(List<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable dataTable = new DataTable();
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
// get the display name for the column to extract
dataTable.Columns.Add(property.DisplayName,
Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
/// <summary>
/// The ExportExcel
/// </summary>
/// <param name="dataTable">The dataTable<see cref="DataTable"/></param>
/// <param name="heading">The heading<see cref="string"/></param>
/// <param name="showSrNo">The showSrNo<see cref="bool"/></param>
/// <param name="sheetName">The sheetName<see cref="string"/></param>
/// <param name="columnsToTake">The columnsToTake<see
cref="string[]"/></param>
/// <returns>The <see cref="byte[]"/></returns>
public static byte[] ExportExcel(DataTable dataTable, string heading = "",
bool showSrNo = false, string sheetName = "Data", params string[] columnsToTake)
{
if (showSrNo)
{
DataColumn dataColumn = dataTable.Columns.Add("#",
typeof(int));
dataColumn.SetOrdinal(0);
int index = 1;
foreach (DataRow item in dataTable.Rows)
{
item[0] = index;
index++;
}
}
var dc = dco.Ordinal + 1;
for (int i = 0; i <= dataTable.Rows.Count; i++)
{
workSheet.Cells[2 + i, dc, i + 2, dc].Value =
(workSheet.Cells[2 + i, dc, i + 2, dc].Value !=
null &&
workSheet.Cells[2 + i, dc, i + 2,
dc].Value.ToString() != string.Empty)
? Convert.ToDecimal(workSheet.Cells[2 + i, dc,
i + 2, dc].Value)
.ToString(decimalFormat, new
CultureInfo("en-US"))
: string.Empty;
}
}
r.Style.Font.Color.SetColor(System.Drawing.Color.White);
r.Style.Font.Bold = true;
r.Style.Fill.PatternType =
OfficeOpenXml.Style.ExcelFillStyle.Solid;
r.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#1fb
5ad"));
}
r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
}
if (!String.IsNullOrEmpty(heading))
{
workSheet.Cells["A1"].Value = heading;
workSheet.Cells["A1"].Style.Font.Size = 20;
workSheet.InsertColumn(1, 1);
workSheet.InsertRow(1, 1);
workSheet.Column(1).Width = 5;
}
result = package.GetAsByteArray();
}
return result;
}
public static byte[] ExportExcel(DataTable dataTable, string heading = "",
bool showSrNo = false, string sheetName = "Data")
{
if (showSrNo)
{
DataColumn dataColumn = dataTable.Columns.Add("#",
typeof(int));
dataColumn.SetOrdinal(0);
int index = 1;
foreach (DataRow item in dataTable.Rows)
{
item[0] = index;
index++;
}
}
var dc = dco.Ordinal + 1;
for (int i = 0; i <= dataTable.Rows.Count; i++)
{
workSheet.Cells[2 + i, dc, i + 2, dc].Value =
(workSheet.Cells[2 + i, dc, i + 2, dc].Value !=
null &&
workSheet.Cells[2 + i, dc, i + 2,
dc].Value.ToString() != string.Empty)
? Convert.ToDecimal(workSheet.Cells[2 + i, dc,
i + 2, dc].Value)
.ToString(decimalFormat, new
CultureInfo("en-US"))
: string.Empty;
}
}
r.Style.Font.Color.SetColor(System.Drawing.Color.White);
r.Style.Font.Bold = true;
r.Style.Fill.PatternType =
OfficeOpenXml.Style.ExcelFillStyle.Solid;
r.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#1fb
5ad"));
}
r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
}
if (!String.IsNullOrEmpty(heading))
{
workSheet.Cells["A1"].Value = heading;
workSheet.Cells["A1"].Style.Font.Size = 20;
workSheet.InsertColumn(1, 1);
workSheet.InsertRow(1, 1);
workSheet.Column(1).Width = 5;
}
result = package.GetAsByteArray();
}
return result;
}
/// <summary>
/// The ExportExcel
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">The data<see cref="List{T}"/></param>
/// <param name="Heading">The Heading<see cref="string"/></param>
/// <param name="showSlno">The showSlno<see cref="bool"/></param>
/// <param name="sheetName">The sheetName<see cref="string"/></param>
/// <param name="ColumnsToTake">The ColumnsToTake<see
cref="string[]"/></param>
/// <returns>The <see cref="byte[]"/></returns>
public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool
showSlno = false, string sheetName = "Data", params string[] ColumnsToTake)
{
return ExportExcel(ListToDataTable<T>(data), Heading, showSlno,
sheetName, ColumnsToTake);
}
}
}
/// <summary>
/// Defines the PolicyExcelHeader
/// </summary>
public static string[] PolicyExcelHeader =
{
"Region", "Policy Number", "Insured Name", "Broker", "Policy Effective
Date", "Policy Expiration Date",
"Transaction Type", "Endorsement Effective Date", "Currency", "Gross
Premium",
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.4\lib\net45\System.Web.Http.
dll</HintPath>
</Reference>