Sei sulla pagina 1di 11

HTML:

<div class="pull-right icons">


<button class="btn btn-primary" [disabled]="!policyListExists"
[ngClass]="{'cursornotallowed': !!policyList && policyList.length === 0 }"
(click)="exportAsXLSXFromAPI()" title="excel export" type="button"><i class="fa fa-
fw fa-file-excel-o"></i></button>
</div>

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;

// Create the Xhr request object


const xhr = new XMLHttpRequest();
xhr.open('POST', `${environment.baseUrl}${apiUrl}`, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('Authorization', `Bearer ${this.authToken.Access_Token}`);
xhr.responseType = 'blob';

// Xhr callback when we get a result back


// We are not using arrow function because we need the 'this' context
xhr.onreadystatechange = function () {
// We use setTimeout to trigger change detection in Zones
setTimeout(() => {
pending = false;
}, 0);
// If we get an HTTP status OK (200), save the file using fileSaver
if (xhr.readyState === 4 && xhr.status === 200) {
subject.next(this.response);
subject.complete();
}
if (xhr.readyState === 4 && xhr.status === 204) {
subject.error(xhr.status);
subject.complete();
} else if (xhr.readyState === 4 && xhr.status === 206) {
// If get HTTP status PartialContent(206) return error in case download
limit exceeded for export.
subject.error(xhr.status);
subject.complete();
}
};
// Start the Ajax request
const params = JSON.stringify(attachmentUrl);
xhr.send(params);
return subject.asObservable();
}

EXCEL.SERVICE.ts

import { Injectable } from '@angular/core';


import * as FileSaver from 'file-saver';
const EXCEL_TYPE = 'application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';

@Injectable({
providedIn: 'root'
})
export class ExcelService {

constructor() { }

saveAsExcelFile(buffer: any, fileName: string): void {


const data: Blob = new Blob([buffer], { type: EXCEL_TYPE });
const currentDate = new Date();
FileSaver.saveAs(data,
`${fileName}_${currentDate.getMonth() + 1}_${currentDate.getDate()}_$
{currentDate.getFullYear()}${EXCEL_EXTENSION}`);
}
}

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);
}

object[] values = new object[properties.Count];


foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = properties[i].GetValue(item);
}

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)
{

byte[] result = null;


string decimalFormat = string.Empty;
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet workSheet =
package.Workbook.Worksheets.Add(string.Format("{0} " + sheetName, heading));
int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;

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++;
}
}

// add the content into the Excel file


workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable,
true);
using (ExcelRange r = workSheet.Cells[startRowFrom, 1,
startRowFrom, dataTable.Columns.Count])
{
var dateColumns = from DataColumn d in dataTable.Columns
where d.DataType == typeof(DateTime) ||
d.ColumnName.Contains("Date")
select d.Ordinal + 1;
foreach (var dc in dateColumns)
{
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.ToDateTime(workSheet.Cells[2 + i, dc,
i + 2, dc].Value)
.ToString("MM/dd/yyyy", new
CultureInfo("en-US")) : string.Empty;
}
}

var currencyColumns = from DataColumn d in dataTable.Columns


where d.DataType == typeof(decimal)
select d;
foreach (var dco in currencyColumns)
{
if (dco.ColumnName.ToLower() != "conversion rate")
decimalFormat = "#,##0.00";
else
decimalFormat = "F9";

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"));
}

// format cells - add borders


using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1,
startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
{
r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
r.Style.Border.Right.Style = ExcelBorderStyle.Thin;

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);
}

// removed ignored columns


for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
{
if (i == 0 && showSrNo)
{
continue;
}
if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
{
workSheet.DeleteColumn(i + 1);
}
}

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")
{

byte[] result = null;


string decimalFormat = string.Empty;
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet workSheet =
package.Workbook.Worksheets.Add(string.Format("{0} " + sheetName, heading));
int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;

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++;
}
}

// add the content into the Excel file


workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable,
true);
using (ExcelRange r = workSheet.Cells[startRowFrom, 1,
startRowFrom, dataTable.Columns.Count])
{
//var dateColumns = from DataColumn d in dataTable.Columns
// where d.DataType == typeof(DateTime) ||
d.ColumnName.Contains("Date")
// select d.Ordinal + 1;
var dateColumns =new List<int>();
foreach (var dc in dateColumns)
{
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.ToDateTime(workSheet.Cells[2 + i, dc,
i + 2, dc].Value)
.ToString("MM/dd/yyyy", new
CultureInfo("en-US")) : string.Empty;
}
}

var currencyColumns = from DataColumn d in dataTable.Columns


where d.DataType == typeof(decimal)
select d;
foreach (var dco in currencyColumns)
{
if (dco.ColumnName.ToLower() != "conversion rate")
decimalFormat = "#,##0.00";
else
decimalFormat = "F9";

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"));
}

// format cells - add borders


using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1,
startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
{
r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
r.Style.Border.Right.Style = ExcelBorderStyle.Thin;

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);
}
}
}

Constants for Excel Header (Example):

/// <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",

"Net Premium", "Payment Plan", "Invoice Status", "User Name", "Broker


Code", "Policy Id",
"Multinational", "Unique Key", "Work item /Submission no.",
"Affiliation", "BHSI Net premium in USD $","Broker Contact
Person","Broker Contact Person's Email","Broker City",

"Broker State","Broker Country","Broker Contact Person's Phone


No.","Certificate/Bond Number","Company Paper","Conversion Rate",
"Converted Premium","Credited Office","DBA Name","Direct/Assumed",

"Exchange Rate as on","Reinsured Company","Invoicing Contact


Email","Invoicing Contact Name","Insured Mailing Address line 1",
"Insured Zip Code","Insured City","Insured State","Insured
Country","Insured Contact Person",

"Insured Contact Person's Email","Insured Contact Person's Phone


No.","Issuing Office","Issuing Underwriter email id","Issuing Underwriter",
"Limit in Local Currency","New/Renewal","Policy Comm in Local
Currency","Policy Commission in USD $","Premium in USD",

"Policy Commission %","Policy Type","Product Line","Product Line


Subtype","Project Name",
"Profit Code","Project Owner Name","Risk Country","Section","Source
System Name",

"Transaction Date","Sync Date"


};
<Reference Include="System.Web.Http, Version=5.2.4.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">

<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.4\lib\net45\System.Web.Http.
dll</HintPath>
</Reference>

Potrebbero piacerti anche