Here we are viewing elements inside the div tag or table. Then get the div or table element using jquery and then read all Class names and convert it into inline styles, then pass it to server side through hidden field and then make process to convert as excel or pdf
In Design Page
In design page add the following code
<div style="float:right;">
<asp:Button ID="btnExport" runat="server" OnClick="btnExport_Click" CssClass="btn btnexcel" OnClientClick="return fnExportExcel();"/>
<asp:Button ID="btnPDF" runat="server" OnClick="btnPDF_Click" CssClass="btn btnPDF" OnClientClick="return fnExportPDF();"/>
<input id="btnPrint" type="button" class="btn btnPrint" />
</div>
<div id="divContent" style="display: none;">
<table cellpadding="0" cellspacing="0" style="width: 100%;" id="tblMain">
<tr>
<td align='left'>
<table id="tblFundDtlView" cellspacing="0" class="tblGP">
<tr>
<td> ......</td>
</tr>
.
.
.
.
</table>
</td>
</tr>
<tr height="12">
<td>
</td>
</tr>
<tr>
<td align='left'>
<div id="divtblGrid">
<table id="tbl_Grid" border="0" cellspacing="0" width="100%">
<tr>
<td> ......</td>
</tr>
.
.
.
.
</table>
<div id="pager">
</div>
</div>
</td>
</tr>
</table>
</div>
In Script Add the following codes
<script type="text/javascript">
//Export Functionalities
//Button Export Functionalities
function fnExportExcel() {
var rowRemTbls = ["#tblFundDtlView"];
exportData("#tblFundDtlView","Excel");
}
function fnExportPDF() {
var rowRemTbls = ["#tblFundDtlView"];
exportData("#tblFundDtlView", "PDF");
}
//Export To Excel and PDF Functionalities
//<----------------------------Start----------------------------->
function exportData(divName, conProc) {
var html;
html =$(ieInnerHTML($(divName)[0], false));
$.each(html.find("* tr"), function() {
if ($(this).css("display") == 'none') {
$(this).remove();
}
});
var retHTML;
if (conProc == "Excel")
retHTML = replaceClassToInline(html);
else (conProc == "PDF")
retHTML = html;
var emptyTable = $("<table><tr><td> </td></tr></table>");
var cloneDiv = $("<div />").append(retHTML);
retHTML = ieInnerHTML($(cloneDiv).html(), false);
$("#ctl00_ContentPlaceHolder1_hidExportData").val("");
$("#ctl00_ContentPlaceHolder1_hidExportData").val(encodeURIComponent(retHTML));
}
function replaceClassToInline(html) {
var aStyleSheets = document.styleSheets;
$.each(document.styleSheets, function(sheetIndex, sheet) {
var sIndex = sheetIndex;
$.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
var ruleIndex = ruleIndex;
var cssText;
if (rule.cssText != undefined) {
cssText = rule.cssText.replace(/(\{|;)\s+/g, "\$1\n ").replace(/\A\s+}/, "}").replace("}", "").split("{");
cssText = cssText[1];
}
else
cssText = $(rule).css("cssText");
var selectorText = rule.selectorText;
if ($.trim(selectorText).substr(0, 1) == "." && cssText != undefined && cssText != '') {
if (selectorText.indexOf("grad1") != -1)
var a = "";
$.each(selectorText.split('.'), function() {
if ($.trim(this) != '' && $.trim(this) != undefined) {
var cName = $.trim(this);
cName = cName.replace(',', '');
try {
$.each(cName.split('.'), function() {
if ($.trim(this) != '' && $.trim(this) != undefined) {
var rows;
$.each(this.split(' '), function() {
var conClass = $.trim(this);
$.each(html.find("." + this), function() {
if (cssText.indexOf('background: url("../images/table/Plus_min.png") no-repeat left 8px;') == -1)
cssText = cssText.replace('background: url("../images/table/Plus_min.png") no-repeat left 8px;', '');
if ($(this).attr("style")) {
var style = $(this).attr("style") + ";" + cssText;
$(this).attr("style", style);
}
else {
$(this).attr("style", cssText);
}
$(this).css('height', '');
$(this).removeClass(conClass);
});
});
}
});
}
catch (e) { }
}
});
}
});
});
return html[0];
}
function ieInnerHTML(obj, convertToLowerCase) {
var zz = obj.innerHTML ? String(obj.innerHTML) : obj
, z = zz.match(/(<.+[^>])/g);
if (z) {
for (var i = 0; i < z.length; (i = i + 1)) {
var y
, zSaved = z[i]
, attrRE = /\=[a-zA-Z\.\:\[\]_\(\)\&\$\%#\@\!0-9\/]+[?\s+|?>]/g;
z[i] = z[i]
.replace(/([<|<\/].+?\w+).+[^>]/,
function(a) {
//return a.toLowerCase();
return a;
});
y = z[i].match(attrRE);
if (y) {
var j = 0
, len = y.length
while (j < len) {
var replaceRE =
/(\=)([a-zA-Z\.\:\[\]_\(\)\&\$\%#\@\!0-9\/]+)?([\s+|?>])/g
, replacer = function() {
var args = Array.prototype.slice.call(arguments);
return '="' + (convertToLowerCase ? args[2].toLowerCase() : args[2]) + '"' + args[3];
//return '="' + args[2] + '"' + args[3];
};
z[i] = z[i].replace(y[j], y[j].replace(replaceRE, replacer));
j += 1;
}
}
zz = zz.replace(zSaved, z[i]);
}
}
return zz;
}
</script>
Then in .cs Page Add the following code
protected void btnExport_Click(object sender, EventArgs e)
{
exportToExcel(hidExportData.Value.Trim());
hidExportData.Value = "";
}
protected void btnPDF_Click(object sender, EventArgs e)
{
exportToPDF(hidExportData.Value.Trim());
hidExportData.Value = "";
}
public void exportToPDF(string html)
{
string strHTML = Regex.Replace(HttpContext.Current.Server.UrlDecode((html)), @"\s+", " ");
strHTML = Regex.Replace(strHTML, "</?(a|A).*?>", "");
strHTML = strHTML.Replace("Loading...", "");
strHTML = strHTML.Replace("javascript:void(0)", "#");
////reset response
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
////define pdf filename
string strFileName = "Report.pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
//get html
string outXml = strHTML;
//Generate PDF
using (Document document = new Document((PageSize.TABLOID), 10, 10, 10, 10))
{
//define output control HTML
MemoryStream memStream = new MemoryStream();
TextReader xmlString = new StringReader(outXml);
PdfWriter writer = PdfWriter.GetInstance(document, memStream);
//open doc
document.Open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
//htmlContext.SetImageProvider(new ImageProvider());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(HttpContext.Current.Server.MapPath("~/css/ExportCss.css"), true);
//cssResolver.AddCssFile(Server.MapPath("~/css/common.css"), true);
cssResolver.AddCssFile(HttpContext.Current.Server.MapPath("~/css/ui.jqgrid.css"), true);
cssResolver.AddCssFile(HttpContext.Current.Server.MapPath("~/css/custom-theme/jquery-ui-1.10.3.custom.min.css"), true);
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser xmlParse = new XMLParser(true, worker);
xmlParse.Parse(xmlString);
xmlParse.Flush();
document.Close();
document.Dispose();
HttpContext.Current.Response.BinaryWrite(memStream.ToArray());
}
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
}
public void exportToExcel(string strHTML)
{
String html = stringBuilder.Append(Regex.Replace(HttpContext.Current.Server.UrlDecode((strHTML)), @"\s+", " ")).ToString();
html = Regex.Replace(html, "</?(a|A).*?>", "");
html = html.Replace("Loading...", "");
html = html.Replace("javascript:void(0)", "#");
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Report.xls");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Write(html);
HttpContext.Current.Response.End();
}
After that download the follwing dll and extract it to your project bin folder then add reference of those dll files
links are:
Note : In both links download the latest versions