Fórum Gerar arquivo excel #9246
10/09/2009
0
'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.
Curtir tópico
+ 0Posts
10/09/2009
Rafael Mello.
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
11/09/2009
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
11/09/2009
Rafael Mello.
Gostei + 0
11/09/2009
Luiz Maia
Gostei + 0
11/09/2009
Rafael Mello.
Gostei + 0
14/09/2009
Luiz Maia
Gostei + 0
17/09/2009
Luiz Maia
Gostei + 0
24/09/2009
Devmedia
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
Clique aqui para fazer login e interagir na Comunidade :)