I would like to add a button to export excel from ASP gridview.
Group INV into "data" sheet
Change header from INV to REF & LINE to LN into "details" sheet
Add One column header "FLAG" into "details" sheet
Add row 2
Who can help me to modify below code by VB?
Protected Sub btnconvert_Click(sender As Object, e As EventArgs) Handles btnconvert.Click
Dim strDateTime As String = Format(Now(), "yyyyMMdd-HHmmss")
Response.ClearContent()
Response.AddHeader("content-disposition", "attachment; filename=HRS-SO-" & strDateTime & ".xls")
Response.ContentType = "application/excel"
Dim sw As New System.IO.StringWriter()
Dim htw As New HtmlTextWriter(sw)
Response.Write(sw.ToString())
Response.[End]()
End sub
Gridview1
INV LINE QTY
===============================================
TESTINV001 001 200
TESTINV001 002 200
TESTINV002 001 1000
"data"
REF
INV
===============================================
TESTINV001
TESTINV002
"details"
REF LN QTY FLAG
INV LINE QTY FLAG
===============================================
TESTIN001 001 200
TESTIN001 002 200
TESTIN002 001 1000
<div>
<table class="auto-style4" cellspacing="0" rules="all" border="1" id="GridView1" style="border-collapse:collapse;">
<tbody><tr>
<th scope="col">INV</th><th scope="col">LINE</th><th scope="col">QTY</th>
</tr><tr>
<td>TESTINV001</td><td>001</td><td>200</td>
</tr><tr>
<td>TESTINV001</td><td>002</td><td>200</td>
</tr><tr>
<td>tESTINV002</td><td>001</td><td>1000</td>
</tr>
</tbody></table>
</div>
var tablesToExcel = (function () {
var uri = 'data:application/vnd.ms-excel;base64,'
, tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
+ '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>'
+ '<Styles>'
+ '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
+ '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
+ '</Styles>'
+ '{worksheets}</Workbook>'
, tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
, tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
, base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
return function (tables, wsnames, wbname, appname) {
var ctx = "";
var workbookXML = "";
var worksheetsXML = "";
var rowsXML = "";
for (var i = 0; i < tables.length; i++) {
if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
for (var j = 0; j < tables[i].rows.length; j++) {
rowsXML += '<Row>'
for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
dataValue = (dataValue) ? dataValue : tables[i].rows[j].cells[k].innerHTML;
var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
dataFormula = (dataFormula) ? dataFormula : (appname == 'Calc' && dataType == 'DateTime') ? dataValue : null;
ctx = {
attributeStyleID: (dataStyle == 'Currency' || dataStyle == 'Date') ? ' ss:StyleID="' + dataStyle + '"' : ''
, nameType: (dataType == 'Number' || dataType == 'DateTime' || dataType == 'Boolean' || dataType == 'Error') ? dataType : 'String'
, data: (dataFormula) ? '' : dataValue
, attributeFormula: (dataFormula) ? ' ss:Formula="' + dataFormula + '"' : ''
};
rowsXML += format(tmplCellXML, ctx);
}
rowsXML += '</Row>'
}
ctx = { rows: rowsXML, nameWS: wsnames[i] || 'Sheet' + i };
worksheetsXML += format(tmplWorksheetXML, ctx);
rowsXML = "";
}
ctx = { created: (new Date()).getTime(), worksheets: worksheetsXML };
workbookXML = format(tmplWorkbookXML, ctx);
var link = document.createElement("A");
link.href = uri + base64(workbookXML);
link.download = wbname || 'Workbook.xls';
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
})();
Related
I used to be able to pull traffic source data by reading the __utmz cookie, by doing so I can post the data to an internal conversion tracking database. but now GA doesn't use this cookie and it appears that the other cookies don't have any client-side data we can use.
Are there any other ways we can pull the traffic source data into our own internal db?
You can simulating the Google Analytics Processing Flow and determine the values of traffic sources parameters like source, medium, campaign, ... using a custom JavaScript in page or through Google Tag Manager.
This can be a solution:
function crumbleCookie(a) {
for (var d = document.cookie.split(";"), c = {}, b = 0; b < d.length; b++) {
var e = d[b].substring(0, d[b].indexOf("=")).trim(),
i = d[b].substring(d[b].indexOf("=") + 1, d[b].length).trim();
c[e] = i
}
if (a) return c[a] ? c[a] : null;
return c
}
function bakeCookie(a, d, c, b, e, i) {
var j = new Date;
j.setTime(j.getTime());
c && (c *= 864E5);
j = new Date(j.getTime() + c);
document.cookie = a + "=" + escape(d) + (c ? ";expires=" + j.toGMTString() : "") + (b ? ";path=" + b : "") + (e ? ";domain=" + e : "") + (i ? ";secure" : "")
}
function writeLogic(n) {
var a = getTrafficSource(n, '.example.com'); //Insert your domain here
a = a.replace(/\|{2,}/g, "|");
a = a.replace(/^\|/, "");
a = unescape(a);
bakeCookie(n, a, 182, "/", "", "") // Cookie expiration sets to 182 days
};
function getParam(s, q) {
try{
var match = s.match('[?&]' + q + '=([^&]+)');
return match ? match[1] : '';
} catch(e){
return '';
}
}
function calculateTrafficSource() {
var source='', medium='', campaign='', term='', content='';
var search_engines = [['bing', 'q'], ['google', 'q'], ['yahoo', 'q'], ['baidu', 'q'], ['yandex', 'q'], ['ask', 'q']]; //List of search engines
var ref = document.referrer;
ref = ref.substr(ref.indexOf('//')+2);
ref_domain = ref;
ref_path = '/';
ref_search = '';
// Checks for campaign parameters
var url_search = document.location.search;
if(url_search.indexOf('utm_source') > -1) {
source = getParam(url_search, 'utm_source');
medium = getParam(url_search, 'utm_medium');
campaign = getParam(url_search, 'utm_campaign');
term = getParam(url_search, 'utm_term');
content = getParam(url_search, 'utm_content');
}
else if (getParam(url_search, 'gclid')) {
source = 'google';
medium = 'cpc';
campaign = '(not set)';
}
else if(ref) {
// separate domain, path and query parameters
if (ref.indexOf('/') > -1) {
ref_domain = ref.substr(0,ref.indexOf('/'));
ref_path = ref.substr(ref.indexOf('/'));
if (ref_path.indexOf('?') > -1) {
ref_search = ref_path.substr(ref_path.indexOf('?')+1);
ref_path = ref_path.substr(0, ref_path.indexOf('?'));
}
}
medium = 'referral';
source = ref_domain;
// Extract term for organic source
for (var i=0; i<search_engines.length; i++){
if(ref_domain.indexOf(search_engines[i][0]) > -1){
medium = 'organic';
source = search_engines[i][0];
term = getParam(ref_search, search_engines[i][1]) || '(not provided)';
break;
}
}
}
return {
'source' : source,
'medium' : medium,
'campaign': campaign,
'term' : term,
'content' : content
};
}
function getTrafficSource(cookieName, hostname) {
var trafficSources = calculateTrafficSource();
var source = trafficSources.source.length === 0 ? 'direct' : trafficSources.source;
var medium = trafficSources.medium.length === 0 ? 'none' : trafficSources.medium;
var campaign = trafficSources.campaign.length === 0 ? 'direct' : trafficSources.campaign;
// exception
if(medium === 'referral') {
campaign = '';
}
var rightNow = new Date();
var value = 'source=' + source +
'&medium=' + medium +
'&campaign='+ campaign +
'&term=' + trafficSources.term +
'&content=' + trafficSources.content +
'&date=' + rightNow.toISOString().slice(0,10).replace(/-/g,"");
return value;
}
// Self-invoking function
(function(){
var date = new Date();
var fr_date = date.getUTCFullYear().toString() + ((date.getUTCMonth() < 9) ? '0' + (date.getUTCMonth()+1).toString() : (date.getUTCMonth()+1).toString()) + ((date.getUTCDate() < 10) ? '0' + date.getUTCDate().toString() : date.getUTCDate().toString());
var session = crumbleCookie()['FirstSession'];
if (typeof session == 'undefined') {
writeLogic('FirstSession');
}
else {
writeLogic('ReturningSession');
}
})();
Code here: http://clients.first-rate.com/firstrate/NewSession%20and%20ReturningSession%20cookies.txt
PaymentService.PaymentServiceClient client = new
PaymentService.PaymentServiceClient();
PaymentTransactionDto model = new PaymentTransactionDto();
OrderInvoiceDto invoiceData;
List<ProductRepoDto> products;
List<OrderTaxDto> taxes;
// Check payment status
int chkProduct = 0;
int chkCourse = 0;
int chkProductCourse = 0;
#region Get order details for invoice
var order_details = client.GetOrderDetailsForInvoice(Convert.ToInt32(Oid.Rows[0]["OrderId"]));
invoiceData = new OrderInvoiceDto();
if (order_details != null)
{
invoiceData = AutoMapConverter<PaymentService.OrderInvoiceDto, OrderInvoiceDto>.GetMappedData(order_details);
}
#endregion
#region Get Products list in order
var productList = client.GetOrderItemsByOrderId(Convert.ToInt32(Oid.Rows[0]["OrderId"]));
products = new List<ProductRepoDto>();
if (productList != null && productList.Count() > 0)
{
products = AutoMapConverter<PaymentService.ProductRepoDto, ProductRepoDto>.GetMappedList(productList.ToList());
}
#endregion
#region ADD Taxes
#region check product type
decimal Amount = 0;
foreach (var item in products)
{
if (item.TypeId == 1)
chkCourse = 1;
if (item.TypeId == 2)
chkProduct = 1;
if (chkCourse == 1 && chkProduct == 1)
chkProductCourse = 1;
Amount = Amount + (item.Amount * item.Quantity);
Amount = Amount - item.Discount;
}
#endregion
// Apply taxes
client.AddOrderTaxMappingDetails(Convert.ToInt64(orderid), Amount);
#endregion
#region Get Applied Tax details
var taxesApplied = client.GetOrderAppliedTaxes(Convert.ToInt64(orderid));
taxes = new List<OrderTaxDto>();
if (taxesApplied != null && taxesApplied.Count() > 0)
{
taxes = AutoMapConverter<PaymentService.OrderTaxDto, OrderTaxDto>.GetMappedList(taxesApplied.ToList());
}
#endregion
string pdfbody = System.IO.File.ReadAllText(Server.MapPath("~/Views/Payment/InvoiceView.cshtml"));
Document document = new Document();
string fileName = string.Format("{0}.pdf", invoiceData.OrderNumber);
var fpath = HttpContext.Current.Server.MapPath("~/Document/Payment/Invoice/");
if (!Directory.Exists(fpath))
{
Directory.CreateDirectory(fpath);
}
pdfbody = pdfbody.Replace("$name$", string.Format("{0} {1}", invoiceData.Billing_FirstName, invoiceData.Billing_LastName));
pdfbody = pdfbody.Replace("$address$", invoiceData.Billing_Address);
pdfbody = pdfbody.Replace("$billingCity$", invoiceData.Billing_City);
pdfbody = pdfbody.Replace("$billingPinCode$", invoiceData.Billing_PinCode.ToString());
pdfbody = pdfbody.Replace("$billingState$", invoiceData.Billing_State);
pdfbody = pdfbody.Replace("$billingCountry$", invoiceData.Billing_Country);
//pdfbody = pdfbody.Replace("$netAmt$", invoiceData.NetAmt.ToString());
//pdfbody = pdfbody.Replace("$grossAmt$", invoiceData.GrossAmt.ToString());
//pdfbody = pdfbody.Replace("$discountAmt$", invoiceData.DiscountAmt.ToString());
pdfbody = pdfbody.Replace("$orderNumber$", invoiceData.OrderNumber.Remove(0, 2));
pdfbody = pdfbody.Replace("$orderDate$", CommonFunctions.EpochToIstDate(Convert.ToDouble(invoiceData.OrderDate)));
StringBuilder b = new StringBuilder();
decimal totalAmount = 0;
foreach (var item in products)
{
if (!string.IsNullOrEmpty(item.ActivationKey))
item.ActivationKey = string.Format("Activation Key:{0}", item.ActivationKey);
b.AppendFormat("<tr><td width='60%'>{0}<br/>{1}</td>", item.ProductName, item.ActivationKey);
b.AppendFormat("<td width='10%' align='left'>{0}</td>", item.Quantity);
b.AppendFormat("<td width='30%' align='right'>{0}</td></tr>", (item.Amount * item.Quantity) - item.Discount);
totalAmount = totalAmount + (item.Amount * item.Quantity);
totalAmount = totalAmount - item.Discount;
}
pdfbody = pdfbody.Replace("$OrderDetailsList$", Convert.ToString(b));
if (taxes != null && taxes.Count > 0)
{
b = new StringBuilder();
foreach (var item in taxes)
{
b.AppendFormat("<tr><td width='80%' colspan='2'>{0} ({1}%)</td>", item.TaxName, item.Percentage);
b.AppendFormat("<td width='20%' align='right'>{0}</td></tr>", item.Amount);
}
pdfbody = pdfbody.Replace("$OrderTaxDetailsList$", Convert.ToString(b));
}
else
{
pdfbody = pdfbody.Replace("$OrderTaxDetailsList$", "");
}
pdfbody = pdfbody.Replace("$netAmt$", totalAmount.ToString());
pdfbody = pdfbody.Replace("$rupees$", CommonFunctions.ConvertNumbertoWords(Convert.ToInt32((int)Math.Ceiling(totalAmount))));
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fpath + fileName, FileMode.Create));
document.Open();
StringReader sr = new StringReader(pdfbody);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, sr);
document.Close();
I want to generate pdf invoice.so i am using itextsharp.
but i am getting Index out of bound array at XMLWorkerHelper.
I am using itextsharp.xmlworker.dll, v5.4.5.0
when i try to update itextsharp.xmlworker.dll, v5.4.5.9
this code works fine..but all other modules of my project which use iTextsharp starts getting error.
if this is version problem, then how i add two different dll in bin folder and use it
or it is code related error?
I have to bind an <asp:calendar> with data fetched from a database using a linq query.
Here is the linq code
public List<AllCalander> SearchCalender(int month, int zip, string type, int cause)
{
var xyz = (from m in DB.Calenders
where(m.DateFrom.Value.Month==month || m.Zip==zip || m.ActivityType==type || m.CauseID==cause)
group m by new { m.DateFrom } into grp
select new
{
caustitle = grp.Select(x => x.Caus.CauseTitle),
datfrm = grp.Key.DateFrom,
total = grp.Count()
})
.ToList()
.Select(m => new AllCalander
{
DateFrom =Convert.ToDateTime(m.datfrm),
CauseTitle = string.Join(",", m.caustitle),
Total = m.total
});
My aspx.cs code is here
List<AllCalander> calnder = calbll.SearchCalender(mnth,ZipString,type,causeString);
foreach (var myItem in calnder)
{
string datetime = myItem.DateFrom.ToString();
Literal myEventNameLiteral = new Literal();
myEventNameLiteral.ID = i + myItem.CauseID.ToString();
// string currentcalanderDate = e.Day.Date.Day.ToString() ;
if (string.Equals(DateTime.Parse(datetime).ToString("MMM dd yyyy"), e.Day.Date.ToString("MMM dd yyyy")))
{
string a = myItem.CauseTitle;
if (a != cause)
cause = a;
coun++;
myEventNameLiteral.Mode = LiteralMode.PassThrough;
myEventNameLiteral.Text = "<br /><span style='font-family:verdana; font-size:10px;'>" + myItem.CauseTitle + "(" + myItem.Total + ")"+ " ";
e.Cell.Controls.Add(myEventNameLiteral);
}
i++;
}
but on output it only shows the last value from database instead of showing all the data.
Can somebody please tell me what's wrong?
Thanks in advance
group m by new { m.DateFrom, m.Caus.CauseTitle } into grp
I have a precompiled template called "ReportOptions_Timeframe". When I call Handlebars.templates.ReportOptions_Timeframe(data) I do not get the rendered template html. Instead I get this for output:
"function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers,
Handlebars.helpers); data = data || {}; var buffer = "", stack1,
helper, functionType="function",
escapeExpression=this.escapeExpression, self=this;
function program1(depth0,data) {
var buffer = ""; buffer += "\r\n "
+ escapeExpression((typeof depth0 === functionType ? depth0.apply(depth0) : depth0))
+ "\r\n "; return buffer; }
buffer += "Term:\r\n\r\n "; stack1 = helpers.each.call(depth0,
(depth0 && depth0.TermList),
{hash:{},inverse:self.noop,fn:self.program(1, program1,
data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "\r\n\r\n\r\n \r\n\r\nDate range:\r\n\r\nto\r\n"; return buffer; }"
What am I doing wrong?
Edited to add the precompiled template:
(function() { var template = Handlebars.template, templates =
Handlebars.templates = Handlebars.templates || {};
templates['ReportOptions_Timeframe'] = template(function
(Handlebars,depth0,helpers,partials,data) { this.compilerInfo =
[4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers);
data = data || {};
return "function (Handlebars,depth0,helpers,partials,data) {\n
this.compilerInfo = [4,'>= 1.0.0'];\nhelpers = this.merge(helpers,
Handlebars.helpers); data = data || {};\n var buffer = \"\", stack1,
helper, functionType=\"function\",
escapeExpression=this.escapeExpression, self=this;\n\nfunction
program1(depth0,data) {\n \n var buffer = \"\";\n buffer +=
\"\r\n \"\n + escapeExpression((typeof depth0 === functionType ? depth0.apply(depth0) : depth0))\n + \"\r\n \";\n return
buffer;\n }\n\n buffer += \"Term:\r\n\r\n \";\n stack1 =
helpers.each.call(depth0, (depth0 && depth0.TermList),
{hash:{},inverse:self.noop,fn:self.program(1, program1,
data),data:data});\n if(stack1 || stack1 === 0) { buffer += stack1;
}\n buffer += \"\r\n\r\n\r\n \r\n\r\nDate range:\r\n\r\nto\r\n\";\n return buffer;\n }"; }); })();
I was giving node the wrong input file. The input file I was using had been previously precompiled.
I am using the Extjs4 multigrouping plugin from here.
I have used it successfully, however i want to show the summary of the totals of each column within the group header itself . how do i set up the appropriate CSS for that ?
In Multigrouping.js
getFragmentTpl: function() {
var me = this;
return {
indentByDepth: me.indentByDepth,
depthToIndent: me.depthToIndent,
renderGroupHeaderTpl: function(values, parent) {
return Ext.XTemplate.getTpl(me, 'groupHeaderTpl').apply(values, parent);
//var z = new Ext.XTemplate('{name} ({rows.grouplength})');
//return z.apply(values, parent);
}
};
},
In my grid
features: [
{
ftype:'multigrouping',
groupHeaderTpl: [
'{[this.readOut(values)]}',
{
readOut:function(values) {
debugger;
var sum1 =0 ,sum2=0,sum3=0;
for( var i = 0 ; i< values.records.length ; i++)
{
var val = parseFloat(values.records[i].data.d2012.mp);
sum1 += isNaN(val) ? 0.0 : val;
val = parseFloat(values.records[i].data.d2013.mp);
sum2 += isNaN(val) ? 0.0 : val;
val = parseFloat(values.records[i].data.d2014.mp);
sum3 += isNaN(val) ? 0.0 : val;
}
return values.name + '(' + values.records.length + ')' + ' ' + sum1.toFixed(2) + ' ' + sum2.toFixed(2) + ' ' + sum3.toFixed(2);
}
}
]
},
had to resort to a few hacks to get this to work. still waiting on an official answer.
The main reason i had to do this and not use the multigrouping summary is because
- i want to limit the number of records from the server. I can do some smart grouping of
my business objects at the server side.
- the main reason to do this is because of IE8's performance on larger sets of data.
- had already tried the extjs4 tree grid component which works well on chrome but had performance issues on IE8.
the hack is to
a) use an array property in the grid to store the dom elements which i want to manipulate
b) use a boolean to know when the layout is completed the first time
b) add listeners for afterlayout ( when your app can do an Ext.get('..dom element..') you know you are done )
The listener :
listeners :
{
afterlayout : function(eopts)
{
var x = this.mOwnArray;
if(!this.loadedwithVals && x.length > 0)
{
for(var i =0 ; i<x.length ; i++)
{
var dom = Ext.get(x[i].id);
var theId = dom.id;
theId = theId.match(/\d+/)[0];
var title = dom.query("td[class='x-grid-cell x-grid-cell-first']");
title[0].className = 'x-grid-cell x-grid-cell-gridcolumn-' + theId + ' x-grid-cell-first';
title[0].colSpan=1;
var groupedHeader = dom.query("div[class='x-grid-group-title']");
groupedHeader[0].innerHTML = x[i].name + '(' + x[i].length + ')';
for(var year=2012;year<=2018;year++)
{
var t = "t"+year;
var someText1 = '<td class=" x-grid-cell x-grid-cell-numbercolumn">';
var someText2 = '<div class="x-grid-cell-inner " style="text-align: left; ;">';
var someText3 = '<div class="x-grid-group-title">' + x[i].total[t] + '</div></div></td>';
var someText = someText1 + someText2 + someText3;
dom.insertHtml("beforeEnd",someText);
}
}
this.loadedwithVals = true;
}
}
And the feature as in
features: [
{
ftype:'multigrouping',
startCollapsed : true,
groupHeaderTpl: [
'{[this.readOut(values)]}',
{
readOut:function(values) {
var header = new Object();
header.id = values.groupHeaderId;
header.sum = [];
header.total = new Object();
for(var year = 2012 ; year <= 2018 ; year++)
{
var t = "t"+year;
header.total[t] = [];
}
// all the records in this header
for( var i = 0 ; i< values.records.length ; i++)
{
// for all the 'years' in this record
for(var year=2012;year<=2018;year++)
{
var d = "d"+year;
var ct = "t" + year;
var arecord = values.records[i].data;
var val = parseFloat(arecord[d].mp);
val = isNaN(val) ? 0.0 : val;
Ext.Array.push(header.total[ct],val);
}
}
// push the sum of the records into its top level group
for(var year = 2012 ; year <= 2018 ; year++)
{
var t = "t"+year;
var sum = Ext.Array.sum(header.total[t]);
header.total[t] = sum.toFixed(2);
}
header.name = values.name;
header.length = values.records.length;
var headerName = values.name;
if(values.hasOwnProperty('parent'))
{
var parent = values.parent;
headerName = headerName.replace(parent,'');
}
header.name = headerName;
header.length = values.records.length;
Ext.Array.push(grid.mOwnArray,header);
// really not used
return values.name + '(' + values.records.length + ')';
}
}
]
},
]