Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Kalel

Exportação HTML para Excel

Recommended Posts

Pessoal,Alguém já exportou um HTML para Excel sem que a estrutura HTML fique desformatada? Mais ou menos assim, criei um relatório em HTML com os elementos dispostos como eu quero. Quando exporto para word a estrutura fica ok mas quanto exporto para excel a estrutura fica toda desformatada(é exigencia do cliente que seja exportado para excel). Monto meu HTML em um StringBuilder e exporto utilizando Response. Utilizo C#.valeu

Compartilhar este post


Link para o post
Compartilhar em outros sites

amigo tenho uma classe em C# que transforma Grids em Excel, tenho formatado para XLS e HTML

 

PRIMEIRO A CHAMADA PARA A CLASSE

 

 

private void wgProcesso_Export(object sender, ISNet.WebUI.WebGrid.ExportEventArgs e)

{

DataSet dsPSExport = new DataSet();

dsPSExport = (DataSet)Session["ExpandeWG"];

e.ReportInfo.ReportType = "excel";

CustomHTMLHierarchicalReportEngine.Init(dsPSExport, tbProcesso, wgProcesso, e.ReportInfo.ReportName, e.ReportInfo.ReportPath, lblTituloConsulta.Text.ToString(), "");

CustomHTMLHierarchicalReportEngine.Create();

e.ReportInfo.ReportName = e.ReportInfo.ReportName;

e.ReturnValue = false;

}

 

 

A CLASSE.

 

 

public class CustomHTMLHierarchicalReportProcesso

{

static StringBuilder _File;

static string _FileName;

static string _Path;

static string _ConsultDescription;

static string _Footer;

static DataSet _DS;

static WebGrid _WG;

static CultureInfo culInfo;

static int iColumnCount = 0;

static Table _TB;

 

public static void Init(DataSet ds, Table tb, WebGrid wg, string fileName, string path, string sConsultDesc, string sFooter)

{

_TB= tb;

_DS = ds;

_WG = wg;

_FileName = fileName;

_Path = path;

_ConsultDescription = sConsultDesc;

_Footer = sFooter;

culInfo = (_WG.LayoutSettings.GetWebGridCulture()!=null)? _WG.LayoutSettings.GetWebGridCulture() : Thread.CurrentThread.CurrentCulture;

}

 

public static void Create()

{

_File = new StringBuilder();

_File.Append("<html><head>");

_File.Append("<meta http-equiv=Content-Type content=text/html; charset=iso-8859-1/>");

_File.Append("</head>");

_File.Append("<body>");

 

_File.Append("<table cellpadding=0 cellspacing=0 border=0 borderColor=gainsboro>");

_File.Append("<tr></tr>");

_File.Append("<tr><IMG src=imgLogoReport.gif align=absMiddle border=0>");

 

_File.Append(CreateReport(_WG.RootTable, _DS.Tables[_WG.RootTable.DataMember].Rows));

 

if(_Footer != "")

{

_File.Append("<table cellpadding=0 cellspacing=0 border=0 borderColor=gainsboro>");

_File.Append("<tr><td align=center colspan=" + iColumnCount.ToString() + "></td></tr>");

for(int cFooter = 0; cFooter <= (_Footer.Length - 10); cFooter++)

{

if(_ConsultDescription.Substring(cFooter, 2).ToString() == ": ")

{

 

_File.Append("<tr><td align=left bgcolor=cccccc colspan=" + iColumnCount.ToString() + "><B>" + _Footer.Substring(0,(cFooter)).ToString() + "</B></td></tr>");

 

_File.Append("<tr><td align=left bgcolor=ffffff width=100 colspan=" + iColumnCount.ToString() + ">" + _Footer.Substring(cFooter + 1).ToString() + "</td></tr>");

cFooter = _ConsultDescription.Length;

}

}

_File.Append("</table>");

}

_File.Append("</body></html>");

 

StreamWriter s = File.CreateText(_Path + _FileName);

s.Write(_File.ToString());

s.Close();

}

 

static string CreateReport(WebGridTable wTbl, DataRowCollection rowcs)

{

DataRow[] rows = new DataRow[rowcs.Count];

for(int i=0; i<rowcs.Count;i++)

rows=rowcs;

 

return CreateReport(wTbl, rows);

}

 

static string CreateReport(WebGridTable wTbl, DataRow[] rows)

{

PSCrypt PSCryptDecrypt = new PSCrypt();

PSCryptDecrypt.InitializeEngine(PSCrypt.AlgorithmType.Rijndael);

iColumnCount = wTbl.Columns.GetVisibleColumnsCount() - 1;

if(wTbl.ChildTables.Count > 0) iColumnCount = wTbl.ChildTables[0].Columns.GetVisibleColumnsCount();

StringBuilder file = new StringBuilder();

 

//filtro para nao ir Table1 p/ o relatório

if(wTbl.Caption != "Parameter" && wTbl.Caption !="Table1")

{

// DADOS GERAIS - TÍTULO ESTA PEGANDO NO TB.ROWS O NOME DA OPÇÃO DESEJADA Ex(STOCKDALE, FILTRAÇÃO, ETC)

file.Append("<td valign=middle align=center bgcolor=ffffff colspan=" + iColumnCount.ToString() + "><FONT size=4><STRONG>"

+ Regex.Replace(wTbl.Caption + " -"+ _TB.Rows[0].Cells[0].Text.ToString(), "x0020x", " ") + "</STRONG></FONT></td></TR>");

 

file.Append("<tr></tr>");

 

// Data - Período

//file.Append("<td valign=middle align=center bgcolor=ffffff=><B>" +"Relatório de Processo -" +_TB.Rows[0].Cells[0].Text.ToString()+ " + _ConsultDescription +"</B></td>");

file.Append("<td valign=middle align=center bgcolor=ffffff=><B>" +"Relatório de Processo CPKelco " + _ConsultDescription +"</B> </td>");

 

}

file.Append("<table cellpadding=0 cellspacing=0 border=1 borderColor=gainsboro>");

int iCountLines = 0;

for(int cStr = 0; cStr <= (_ConsultDescription.Length - 10); cStr++)

{

if(_ConsultDescription.Substring(cStr, 3).ToString() == "@@@")

{

if(wTbl.Caption != "Parameter") file.Append("<tr><td align=center bgcolor=cccccc colspan=" + iColumnCount.ToString() + ">" + _ConsultDescription.Substring(0,(cStr)).ToString() + "</td></tr>");

if(wTbl.Caption != "Parameter") file.Append("<tr><td align=center bgcolor=cccccc colspan=" + iColumnCount.ToString() + ">" + _ConsultDescription.Substring(cStr + 3).ToString() + "</td></tr>");

cStr = _ConsultDescription.Length;

iCountLines = 2;

}

}

 

if(iCountLines < 2)

{

if(wTbl.Caption != "Parameter") file.Append("<tr><td align=center bgcolor=ffffff colspan=" + iColumnCount.ToString() + ">" + "</td></tr>");

}

 

foreach(WebGridColumn col in wTbl.Columns)

if (col.Visible)

if(col.Caption != "" && col.Caption != "Etapa" && col.Caption.Trim() != "Alterar" && col.Caption !="vc_parametro")

if(col.Caption != " ")

file.Append("<td align=center style=FONT-SIZE: 6pt; FONT-STYLE: bold; FONT-FAMILY: Arial; FONT-VARIANT: normal bgcolor=f5f5f5" + "colspan=" + "1.8" + "><B>" + col.Caption.ToString() + "</B></td>");

object sValue = null;

foreach(DataRow row in rows)

{

file.Append("<tr>");

foreach(WebGridColumn col in wTbl.Columns)

{

if(col.DataMember.ToString() != "vc_reg_valor" && col.DataMember.ToString() != "btn_alterar")

{

if(col.DataMember.ToString() == "vc_user" || col.DataMember.ToString() == "vc_user_full_name" || col.DataMember.ToString() == "i_user_id")

sValue = row[col.DataMember].ToString() != "" ? PSCryptDecrypt.Decrypt(row[col.DataMember].ToString()).ToString() : "";

else

sValue = row[col.DataMember].ToString();

 

if (col.Visible && row.Table.Columns.Contains(col.DataMember) && col.Bound==true && col.DataMember.ToString() != "vc_parametro")

if(wTbl.Caption != "Parameter")

file.Append("<td style=FONT-SIZE: 6pt; FONT-STYLE: normal; FONT-FAMILY: Arial; FONT-VARIANT: normal align=" + GetHorisontalAlign(System.Web.UI.WebControls.HorizontalAlign.Center) + " colspan=" + "1.8" + ">" + GetRenderedData(sValue, row.Table.Columns[col.DataMember].DataType.ToString(), wTbl.Columns.GetNamedItem(col.DataMember).DataFormatString) + "</td>");

else

file.Append("<td style=FONT-SIZE: 6pt; FONT-STYLE: normal; FONT-FAMILY: Arial; FONT-VARIANT: normal align=" + GetHorisontalAlign(System.Web.UI.WebControls.HorizontalAlign.Center) + " colspan=" + "1.8" + ">" + GetRenderedData(sValue, row.Table.Columns[col.DataMember].DataType.ToString(), "") + "</td>");

 

// titulo de cada setor, vazao, volume, etc

if (col.Visible && row.Table.Columns.Contains(col.DataMember) && col.Bound==true && col.DataMember.ToString() == "vc_parametro")

file.Append("<td align=center bgcolor=DDDDDD style=FONT-SIZE: 6pt; FONT-STYLE: normal; FONT-FAMILY: Arial; FONT-VARIANT: normal" + GetHorisontalAlign(System.Web.UI.WebControls.HorizontalAlign.Left) + " colspan=" + "6" + "><B>" + GetRenderedData(sValue, row.Table.Columns[col.DataMember].DataType.ToString(), "") + "</B></td>");

}

}

file.Append("</tr>");

foreach(DataRelation rel in row.Table.ChildRelations)

{

file.Append(CreateReport(wTbl.ChildTables.GetNamedItem(Regex.Replace(rel.ChildTa

ble.TableName, "\\s+", "x0020x")), row.GetChildRows(rel)));

}

}

 

file.Append("</table>");

file.Append("<table>");

 

// espaçador de linhas entre as tabelas

file.Append("<td valign=middle align=center bgcolor=ffffff=><p> </p></td>");

return file.ToString();

}

 

static string GetRenderedData(object dt, string type, string dataFormatString)

{

string val = " ";

if (!dt.Equals(System.DBNull.Value))

switch(type)

{

case "System.Int16" : val = dt.ToString() != "" ? Convert.ToInt16(dt).ToString(dataFormatString, culInfo) : ""; break;

case "System.Int32" : val = dt.ToString() != "" ? Convert.ToInt32(dt).ToString(dataFormatString, culInfo) : ""; break;

case "System.Int64" : val = dt.ToString() != "" ? Convert.ToInt64(dt).ToString(dataFormatString, culInfo) : ""; break;

case "System.UInt16" : val = dt.ToString() != "" ? Convert.ToUInt16(dt).ToString(dataFormatString, culInfo) : ""; break;

case "System.UInt32" : val = dt.ToString() != "" ? Convert.ToUInt32(dt).ToString(dataFormatString, culInfo) : ""; break;

case "System.UInt64" : val = dt.ToString() != "" ? Convert.ToUInt64(dt).ToString(dataFormatString, culInfo) : ""; break;

case "System.Byte" : val = dt.ToString() != "" ? Convert.ToByte(dt).ToString(dataFormatString, culInfo) : ""; break;

case "System.SByte" : val = dt.ToString() != "" ? Convert.ToSByte(dt).ToString(dataFormatString, culInfo) : ""; break;

case "System.Decimal" : val = dt.ToString() != "" ? Convert.ToDecimal(dt).ToString(dataFormatString, culInfo) : ""; break;

case "System.DateTime" : val = dt.ToString() != "" ? Convert.ToDateTime(dt).ToString(dataFormatString, culInfo) : ""; break;

case "System.Double" : val = dt.ToString() != "" ? Convert.ToDouble(dt).ToString(dataFormatString, culInfo) : ""; break;

case "System.Single" : val = dt.ToString() != "" ? Convert.ToSingle(dt).ToString(dataFormatString, culInfo) : ""; break;

case "System.Boolean" : val = dt.ToString() != "" ? Convert.ToBoolean(dt).ToString(culInfo) : ""; break;

case "System.Char" : val = dt.ToString() != "" ? Convert.ToChar(dt).ToString(culInfo) : ""; break;

case "System.String" : val = dt.ToString() != "" ? Convert.ToString(dt.ToString(),culInfo) : ""; break;

}

return val;

}

 

static string GetHorisontalAlign(HorizontalAlign align)

{

string alignString="";

switch(align)

{

case HorizontalAlign.Center : alignString = "center"; break;

case HorizontalAlign.Justify : alignString = "justify"; break;

case HorizontalAlign.Left : alignString = "left"; break;

case HorizontalAlign.Right : alignString = "right"; break;

 

}

return alignString;

}

}

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.