Gerar arquivo excel
Try
Dim dt as dataset
dt.columns.add("id")
dt.columns.add("nome")
'Gera o Pdf
Call Me.GeraExcel(ds)
End If
Catch ex As Exception
Throw New Exception("Erro ao Obter Extrato")
End Try
Private Sub GeraExcel(ByVal ds As DataSet) With Response .Clear()
.Buffer = True
.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
.Charset = ""
.ContentType = "application/vnd.ms-excel" Dim sw As New System.IO.StringWriter()
Dim hw As New HtmlTextWriter(sw) GridView1 = New GridView
GridView1.DataSource = ds
GridView1.AllowPaging = False
GridView1.DataBind() 'Change the Header Row back to white color
Me.GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF") 'Apply style to Individual Cells With GridView1.HeaderRow
For i As Integer = 0 To ds.Tables(0).Columns.Count - 1
.Cells(i).Style.Add("background-color", "green")
.Cells(i).Style.Add("forecolor", "white")
Next
End With For i As Integer = 0 To GridView1.Rows.Count - 1 Dim row As GridViewRow = GridView1.Rows(i) 'Change Color back to white
row.BackColor = System.Drawing.Color.White 'Apply text style to each Row
row.Attributes.Add("class", "textmode") 'Apply style to Individual Cells of Alternating Row If i Mod 2 <> 0 Then For b As Integer = 0 To ds.Tables(0).Columns.Count - 1
row.Cells(b).Style.Add("background-color", "#C2D69B")
Next End If Next GridView1.RenderControl(hw)
'style to format numbers to string
Dim style As String = "<style>.textmode{mso-number-format:\@;}</style>" .Write(style)
.Output.Write(sw.ToString())
.Flush()
.End() End With End Sub
'Gera o Pdf
Call Me.GeraExcel(ds)
End If
Catch ex As Exception
Throw New Exception("Erro ao Obter Extrato")
End Try
Private Sub GeraExcel(ByVal ds As DataSet) With Response .Clear()
.Buffer = True
.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
.Charset = ""
.ContentType = "application/vnd.ms-excel" Dim sw As New System.IO.StringWriter()
Dim hw As New HtmlTextWriter(sw) GridView1 = New GridView
GridView1.DataSource = ds
GridView1.AllowPaging = False
GridView1.DataBind() 'Change the Header Row back to white color
Me.GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF") 'Apply style to Individual Cells With GridView1.HeaderRow
For i As Integer = 0 To ds.Tables(0).Columns.Count - 1
.Cells(i).Style.Add("background-color", "green")
.Cells(i).Style.Add("forecolor", "white")
Next
End With For i As Integer = 0 To GridView1.Rows.Count - 1 Dim row As GridViewRow = GridView1.Rows(i) 'Change Color back to white
row.BackColor = System.Drawing.Color.White 'Apply text style to each Row
row.Attributes.Add("class", "textmode") 'Apply style to Individual Cells of Alternating Row If i Mod 2 <> 0 Then For b As Integer = 0 To ds.Tables(0).Columns.Count - 1
row.Cells(b).Style.Add("background-color", "#C2D69B")
Next End If Next GridView1.RenderControl(hw)
'style to format numbers to string
Dim style As String = "<style>.textmode{mso-number-format:\@;}</style>" .Write(style)
.Output.Write(sw.ToString())
.Flush()
.End() End With End Sub
Rafael Mello.
Curtidas 0
Respostas
Rafael Mello.
10/09/2009
Senhores,
Boa Tarde.
Estou com um problema quando tento gerar um arquivo xls com dados de um dataset em minha aplicação web asp.net 3.5. Estou criando um gridview com colunas e tal. Só consigo gerar o xls se eu fizer um databind no gridview com os dados do dataset. Eu precisava gerar o .xls direto, sem precisar utilizar um gridview para isso.
'codigo do event click co botao
Try
Dim dt as datatable
dt.columns.add("id")
dt.columns.add("nome") Dim linha as datarow = nothing
linha = dt.newRow
linha(0) = "1"
linha(1) = "Ana"
dt.rows.add(linha)
linha = dt.newRow
linha(0) = "2"
linha(1) = "Roberta"
dt.rows.add(linha)
linha = dt.newRow
linha(0) = "3"
linha(1) = "Paula"
dt.rows.add(linha)
linha = dt.newRow
linha(0) = "4"
linha(1) = "Maria"
dt.rows.add(linha) Dim ds as new dataset
ds.Tables.add(dt) 'Gera o Pdf
Call Me.GeraExcel(ds)
Catch ex As Exception
Throw New Exception("Erro ao Obter Extrato")
End Try
'fim do codigo do event click co botao 'Método que gera o excel
Private Sub GeraExcel(ByVal ds As DataSet) With Response .Clear()
.Buffer = True
.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
.Charset = ""
.ContentType = "application/vnd.ms-excel" Dim sw As New System.IO.StringWriter()
Dim hw As New HtmlTextWriter(sw) GridView1 = New GridView
GridView1.DataSource = ds
GridView1.AllowPaging = False
GridView1.DataBind() 'Change the Header Row back to white color
Me.GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF") 'Apply style to Individual Cells With GridView1.HeaderRow
For i As Integer = 0 To ds.Tables(0).Columns.Count - 1
.Cells(i).Style.Add("background-color", "green")
.Cells(i).Style.Add("forecolor", "white")
Next
End With For i As Integer = 0 To GridView1.Rows.Count - 1 Dim row As GridViewRow = GridView1.Rows(i) 'Change Color back to white
row.BackColor = System.Drawing.Color.White 'Apply text style to each Row
row.Attributes.Add("class", "textmode") 'Apply style to Individual Cells of Alternating Row If i Mod 2 <> 0 Then For b As Integer = 0 To ds.Tables(0).Columns.Count - 1
row.Cells(b).Style.Add("background-color", "#C2D69B")
Next End If Next GridView1.RenderControl(hw)
'style to format numbers to string
Dim style As String = "<style>.textmode{mso-number-format:\@;}</style>" .Write(style)
.Output.Write(sw.ToString())
.Flush()
.End() End With End Sub
Agradeço a atenção dispensada. Att... Rafael.
Dim dt as datatable
dt.columns.add("id")
dt.columns.add("nome") Dim linha as datarow = nothing
linha = dt.newRow
linha(0) = "1"
linha(1) = "Ana"
dt.rows.add(linha)
linha = dt.newRow
linha(0) = "2"
linha(1) = "Roberta"
dt.rows.add(linha)
linha = dt.newRow
linha(0) = "3"
linha(1) = "Paula"
dt.rows.add(linha)
linha = dt.newRow
linha(0) = "4"
linha(1) = "Maria"
dt.rows.add(linha) Dim ds as new dataset
ds.Tables.add(dt) 'Gera o Pdf
Call Me.GeraExcel(ds)
Catch ex As Exception
Throw New Exception("Erro ao Obter Extrato")
End Try
'fim do codigo do event click co botao 'Método que gera o excel
Private Sub GeraExcel(ByVal ds As DataSet) With Response .Clear()
.Buffer = True
.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
.Charset = ""
.ContentType = "application/vnd.ms-excel" Dim sw As New System.IO.StringWriter()
Dim hw As New HtmlTextWriter(sw) GridView1 = New GridView
GridView1.DataSource = ds
GridView1.AllowPaging = False
GridView1.DataBind() 'Change the Header Row back to white color
Me.GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF") 'Apply style to Individual Cells With GridView1.HeaderRow
For i As Integer = 0 To ds.Tables(0).Columns.Count - 1
.Cells(i).Style.Add("background-color", "green")
.Cells(i).Style.Add("forecolor", "white")
Next
End With For i As Integer = 0 To GridView1.Rows.Count - 1 Dim row As GridViewRow = GridView1.Rows(i) 'Change Color back to white
row.BackColor = System.Drawing.Color.White 'Apply text style to each Row
row.Attributes.Add("class", "textmode") 'Apply style to Individual Cells of Alternating Row If i Mod 2 <> 0 Then For b As Integer = 0 To ds.Tables(0).Columns.Count - 1
row.Cells(b).Style.Add("background-color", "#C2D69B")
Next End If Next GridView1.RenderControl(hw)
'style to format numbers to string
Dim style As String = "<style>.textmode{mso-number-format:\@;}</style>" .Write(style)
.Output.Write(sw.ToString())
.Flush()
.End() End With End Sub
Agradeço a atenção dispensada. Att... Rafael.
GOSTEI 0
Luiz Maia
10/09/2009
Ola Rafael,
Não precisa do gridView, pode gerar direto sim.
Apenas use o exemplo abaixo:
void BtnExportarClick(object sender, EventArgs e)
{
string caminho = txtNomeArquivoXLS.Text;
if(cboSGBD.SelectedIndex == 0) { // criar um arquivo para escrever using (StreamWriter sw = File.CreateText(caminho)) { //Monta a string de conexão para MS Access com os dados do formulário String conn = @"provider=Microsoft.Jet.OLEDB.4.0;data source = c:\dados\ " + txtBD.Text + ".mdb"; OleDbConnection cn = new OleDbConnection(conn); OleDbCommand cmd = new OleDbCommand("SELECT * FROM " + txtTabela.Text, cn); try { cn.Open(); OleDbDataReader dr = cmd.ExecuteReader(); // percorre o datareader e escreve os dados no arquivo .xls definido while (dr.Read()) { sw.WriteLine(dr["ProductName"].ToString() + "\t" + dr["UnitPrice"].ToString()); } //exibe mensagem ao usuario MessageBox.Show("Arquivo " + caminho + " gerado com sucesso."); } catch (Exception excpt) { MessageBox.Show(excpt.Message); } } } else { // criar um arquivo para escrever using (StreamWriter sw = File.CreateText(caminho)) { //Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=True; //Monta a string de conexão para SQL Server com os dados do formulário string conn = @"Server = " + txtServidor.Text; conn = conn + "; Database = " + txtBD.Text; conn = conn + "; Trusted_Connection=True"; SqlConnection cn = new SqlConnection(conn); //define a instrução SQL para executar contra o banco de dados string sql = " Select * from " + txtTabela.Text; SqlCommand cmd = new SqlCommand(sql, cn); try { //abre a conexão e gera o datareader cn.Open(); SqlDataReader dr = cmd.ExecuteReader(); // percorre o datareader e escreve os dados no arquivo .xls definido while (dr.Read()) { sw.WriteLine(dr["ProductName"].ToString() + "\t" + dr["UnitsInStock"].ToString() + "\t" + dr["UnitPrice"].ToString()); } //exibe mensagem ao usuario MessageBox.Show("Arquivo " + caminho + " gerado com sucesso."); } catch (Exception excpt) { MessageBox.Show(excpt.Message); } } } } Isto gera o excel num caminho especifico, depois é so abri-lo. Abraços e aguardo retorno se conseguiu, ok? Att Luiz Maia
if(cboSGBD.SelectedIndex == 0) { // criar um arquivo para escrever using (StreamWriter sw = File.CreateText(caminho)) { //Monta a string de conexão para MS Access com os dados do formulário String conn = @"provider=Microsoft.Jet.OLEDB.4.0;data source = c:\dados\ " + txtBD.Text + ".mdb"; OleDbConnection cn = new OleDbConnection(conn); OleDbCommand cmd = new OleDbCommand("SELECT * FROM " + txtTabela.Text, cn); try { cn.Open(); OleDbDataReader dr = cmd.ExecuteReader(); // percorre o datareader e escreve os dados no arquivo .xls definido while (dr.Read()) { sw.WriteLine(dr["ProductName"].ToString() + "\t" + dr["UnitPrice"].ToString()); } //exibe mensagem ao usuario MessageBox.Show("Arquivo " + caminho + " gerado com sucesso."); } catch (Exception excpt) { MessageBox.Show(excpt.Message); } } } else { // criar um arquivo para escrever using (StreamWriter sw = File.CreateText(caminho)) { //Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=True; //Monta a string de conexão para SQL Server com os dados do formulário string conn = @"Server = " + txtServidor.Text; conn = conn + "; Database = " + txtBD.Text; conn = conn + "; Trusted_Connection=True"; SqlConnection cn = new SqlConnection(conn); //define a instrução SQL para executar contra o banco de dados string sql = " Select * from " + txtTabela.Text; SqlCommand cmd = new SqlCommand(sql, cn); try { //abre a conexão e gera o datareader cn.Open(); SqlDataReader dr = cmd.ExecuteReader(); // percorre o datareader e escreve os dados no arquivo .xls definido while (dr.Read()) { sw.WriteLine(dr["ProductName"].ToString() + "\t" + dr["UnitsInStock"].ToString() + "\t" + dr["UnitPrice"].ToString()); } //exibe mensagem ao usuario MessageBox.Show("Arquivo " + caminho + " gerado com sucesso."); } catch (Exception excpt) { MessageBox.Show(excpt.Message); } } } } Isto gera o excel num caminho especifico, depois é so abri-lo. Abraços e aguardo retorno se conseguiu, ok? Att Luiz Maia
GOSTEI 0
Rafael Mello.
10/09/2009
Luiz,
Bom Dia. O código é interessante. Mas não irá me atender pq preciso enviar o arquivo no cabeçalho da requisição e não poderei gravar em disco. O projeto é uma aplicação web tenho que gerar o arquivo e enviar para o usuário abrir ou fazer download.
Agradeço a Ajuda.
Att...
Rafael.
GOSTEI 0
Luiz Maia
10/09/2009
Rafael,
Então crie o arquivo, gravei numa pasta temp e depois transforme-o num array de bytes, assim vc consegue atachar num email, e depois vc deleta da pasta temporaria, pode ser assim?
Aguardo
Abraços
Att
Luiz Maia
GOSTEI 0
Rafael Mello.
10/09/2009
Luiz,
Na verdade o que eu não posso fazer é criar o arquivo em disco (pois é um requisito. O usuário exigiu assim). Eu queria criar um stream e em seguida enviar isso para o usuário fazer download/abrir.
Agradeço a ajuda.
Att...
Rafael.
GOSTEI 0
Luiz Maia
10/09/2009
Rafael,
Qual o problema em criar este arquivo numa pasta TEMP, e assim que ele for atachado no email, ele é deletado.
Isto não tem impacto nenhum na aplicação e não "enche" o servidor também.
E ainda tem uma vantagem, vc tem como fazer um tratamento no sentido de, se o email não for enviado com sucesso, vc pode deixar o arquivo excel no servidor e fazer um recurso para ler estes arquivos, assim vc tera um controle maior sobre estes envios, e permitira vc reenviar estes emails que não foram enviados anteriormente.
Aguardo contato, ok?
Caso esta solução não te atenda, vamos propor outra, oi?
Abraços
Att
Luiz Maia
GOSTEI 0
Luiz Maia
10/09/2009
Ola Rafael,
Alguma posição?
Aguardo respostas.
Abraços
Att
Luiz Maia
GOSTEI 0
Devmedia
10/09/2009
Rafael,
por falta de retorno estamos concluindo o seu chamado. Caso ainda tenha dúvidas sobre o assunto aqui tratado, por favor, volte a postar aqui mesmo que o consultor voltará a lhe atender.
por falta de retorno estamos concluindo o seu chamado. Caso ainda tenha dúvidas sobre o assunto aqui tratado, por favor, volte a postar aqui mesmo que o consultor voltará a lhe atender.
GOSTEI 0