Fernando Cruz's profileFernando CruzPhotosBlogListsMore Tools Help

Fernando Cruz

Fernando

Occupation
There are no categories in use.
There are no photo albums.
No list items have been added yet.
November 19

Exportar um datatable para .doc, .xls, .txt, .pdf e .csv

Boa tarde pessoal, abaixo tem alguns métodos que utilizei para exportar um datatable, que na minha aplicação está preenchendo um gridview. Nester métodos abaixo o datatable pode ser exportado para os seguintes formatos: .pdf, .txt, .xls, .doc e .csv.

/// <summary>
/// M‚todo que exporta um datatable para documento Excel
/// </summary>
public void ExportarExcel()
{
System.Data.DataTable tb = (System.Data.DataTable)Session["tb"];
StringBuilder str = new StringBuilder();
str.Append("Relat¢rio de Itens da Solicita‡Æo<br /><br />");
int borderWidth = 1;
string boldTagStart = "<b>";
string boldTagEnd = "</b>";
str.Append("<table border=" + borderWidth + ">");
str.Append("<tr>");
foreach (DataColumn oDataColumn in tb.Columns)
{
str.Append("<td>" + boldTagStart + oDataColumn.ColumnName + boldTagEnd + "</td>");
}
str.Append("</tr>");
foreach (DataRow oDataRow in tb.Rows)
{
str.Append("<tr>");
foreach (DataColumn oDataColumn in tb.Columns)
{
if (oDataRow[oDataColumn.ColumnName] is long)
{
str.Append("<td align="right">" + oDataRow[oDataColumn.ColumnName].ToString() + "</td>");
}
else
{
str.Append("<td>" + oDataRow[oDataColumn.ColumnName].ToString() + "</td>");
}
}
str.Append("</tr>");
}
str.Append("</table>");
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=filename.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
Response.Write(str.ToString());
Response.End();
}

/// <summary>
/// M‚todo que exporta um datatable para documento Word
/// </summary>
public void ExportarWord()
{
System.Data.DataTable tb = (System.Data.DataTable)Session["tb"];
StringBuilder str = new StringBuilder();
str.Append("Relat¢rio de Itens da Solicita‡Æo<br /><br />");
int borderWidth = 1;
string boldTagStart = "<b>";
string boldTagEnd = "</b>";
str.Append("<table border=" + borderWidth + ">");
str.Append("<tr>");
foreach (DataColumn oDataColumn in tb.Columns)
{
str.Append("<td>" + boldTagStart + oDataColumn.ColumnName + boldTagEnd + "</td>");
}
str.Append("</tr>");
foreach (DataRow oDataRow in tb.Rows)
{
str.Append("<tr>");
foreach (DataColumn oDataColumn in tb.Columns)
{
if (oDataRow[oDataColumn.ColumnName] is long)
{
str.Append("<td align="right">" + oDataRow[oDataColumn.ColumnName].ToString() + "</td>");
}
else
{
str.Append("<td>" + oDataRow[oDataColumn.ColumnName].ToString() + "</td>");
}
}
str.Append("</tr>");
}
str.Append("</table>");
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
Response.Write(str.ToString());
Response.End();
}

/// <summary>
/// M‚todo que exporta um datatable para .txt
/// </summary>
public void ExportarTxt()
{
System.Data.DataTable dt = (System.Data.DataTable)Session["tb"];
StringBuilder str = new StringBuilder();
int[] maior = ObterMaiorString(); //obt‚m o vetor com as colunas com as maiores quantidades de caracteres.
str.Append("-------> RELATàRIO DE Itens da Solicita‡Æo <---------\r\n");
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j <= dt.Columns.Count - 1; j++)
{
int aux = maior[j] - dt.Rows[i][j].ToString().Length;
string espacos = "";
for (int x = 0; x < (maior[j] - dt.Rows[i][j].ToString().Length); x++)
{
espacos += " ";
}
str.Append(dt.Rows[i][j].ToString() + espacos + " ");
}
str.Append("\r\n");
}
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.txt");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.text";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
Response.Write(str.ToString());
Response.End();
}

/// <summary>
/// M‚todo que exportar um datatable para pdf usando a dll itextsharp
/// </summary>
public void ExportarPDF()
{
Response.Clear();
Document document = new Document(PageSize.A4.Rotate(), 80, 50, 30, 65);
StringBuilder strData = new StringBuilder(string.Empty);
string strHTMLpath = Server.MapPath("MyHTML.html");
string strPDFpath = Server.MapPath("MyPDF.pdf");
try
{
System.Data.DataTable tb = (System.Data.DataTable)Session["tb"];
StringBuilder str = new StringBuilder();
str.Append("Relat¢rio de Itens da Solicita‡Æo<br /><br />");
str.Append("<table border="1">");
str.Append("<tr>");
foreach (DataColumn oDataColumn in tb.Columns)
{
str.Append("<td><b>" + oDataColumn.ColumnName + "</b></td>");
}
str.Append("</tr>");
foreach (DataRow oDataRow in tb.Rows)
{
str.Append("<tr>");
foreach (DataColumn oDataColumn in tb.Columns)
{
if (oDataRow[oDataColumn.ColumnName] is long)
{
str.Append("<td align="right">" + oDataRow[oDataColumn.ColumnName].ToString() + "</td>");
}
else
{
str.Append("<td>" + oDataRow[oDataColumn.ColumnName].ToString() + "</td>");
}
}
str.Append("</tr>");
}
str.Append("</table>");
StringWriter sw = new StringWriter();
sw.Write(str);
HtmlTextWriter htw = new HtmlTextWriter(sw);
StreamWriter strWriter = new StreamWriter(strHTMLpath, false, Encoding.UTF8);
strWriter.Write("<html><head><link href="Style.css" rel="stylesheet" type="text/css"></head><body>" + htw.InnerWriter.ToString() + "</body></html>");
strWriter.Close();
strWriter.Dispose();
iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
styles.LoadTagStyle("ol", "leading", "16,0");
PdfWriter.GetInstance(document, new FileStream(strPDFpath, FileMode.Create));
document.Add(new Header(iTextSharp.text.html.Markup.HTML_ATTR_STYLESHEET, "Style.css"));
document.Open();
ArrayList objects;
styles.LoadTagStyle("li", "face", "garamond");
styles.LoadTagStyle("span", "size", "8px");
styles.LoadTagStyle("body", "font-family", "times new roman");
styles.LoadTagStyle("body", "font-size", "10px");
document.NewPage();
objects = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StreamReader(strHTMLpath, Encoding.Default), styles);
for (int k = 0; k < objects.Count; k++)
{
document.Add((IElement)objects[k]);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
document.Close();
Response.Write(Server.MapPath(".") + "\\MyPDF.pdf");
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + strPDFpath);
Response.ContentType = "application/octet-stream";
Response.WriteFile(Server.MapPath(".") + "\\MyPDF.pdf");
Response.Flush();
Response.Close();
if (File.Exists(Server.MapPath(".") + "\\MyPDF.pdf"))
{
File.Delete(Server.MapPath(".") + <a href="\\MyPDF.pdffile://mypdf.pdf/">\\MyPDF.pdf</a>);
}
}
}

/// <summary>
/// M‚todo que exporta um datatable para CSV
/// </summary>
public void ExportarCSV()
{
System.Data.DataTable dt = (System.Data.DataTable)Session["tb"];
StringBuilder str = new StringBuilder();
str.AppendLine("Relat¢rio de Itens da Solicita‡Æo");
foreach (DataColumn oDataColumn in dt.Columns)
{
str.Append(oDataColumn.ColumnName + "");
}
foreach (DataRow oDataRow in dt.Rows)
{
str.AppendLine();
for (int i = 0; i < dt.Columns.Count; i++)
{
str.Append(oDataRow[i] + "");
}
}
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=FileName.csv");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "text/plain";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
Response.Write(str.ToString());
Response.End();
}
Percebam que nos métodos acima o datatable estou passando através de uma session chamada session["tb"]. Agraços e até a próxima.
October 22

Meu blog

 
Public folders