Exportar para Excel
-
22-08-2019 - |
Pergunta
Gostaria de exportar um GridView para excel, que é bastante fácil. Mas acima da grade, no Excel, gostaria algumas outras informações para identificação. Posso alguma forma exportar outras coisas que gridviews enquanto seguida, colocar na gridview abaixo?
Editar: Por alguma razão, quando o GridView1 é visível e tento exportar, toda a exportação de página e não apenas o gridview. Não sei por que!
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
'Create a StringWriter and HtmlTextWriter
Dim sw As System.IO.StringWriter = New System.IO.StringWriter()
Dim htw As New System.Web.UI.HtmlTextWriter(sw)
'Clear the Response object's content and specify the header for the HTML response and type of application file to create
Response.ClearContent()
Response.AddHeader("content-disposition", "attachment; filename=SaveFile.xls")
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
EnableViewState = False
htw.WriteLine("Test, test, test")
Try
'Check for the number of GridView rows
If GridView1.Rows.Count < 65535 Then
'Turn sorting and paging off and rebind the GridView control
GridView1.AllowSorting = False
GridView1.AllowPaging = False
GridView1.PageSize = GridView1.Rows.Count
GridView1.AutoGenerateSelectButton() = False
GridView1.DataBind()
'Render the GridView1 as HTML - this will cause an error that will fire the VerifyRenderingInServerForm event -- this event is trapped by the Overriding sub procedure given at the end of the program listing
GridView1.RenderControl(htw)
'Write the response
Response.Write(sw.ToString())
Response.End()
'Turn sorting and paging on and rebind the GridView control
GridView1.AllowSorting = True
GridView1.AllowPaging = True
'.GridView1.PageSize = 10
GridView1.AutoGenerateSelectButton() = True
GridView1.DataBind()
End If
Catch ex As Exception
End Try
End Sub
Solução
Sim, pode.
fazer algo como isto:
HttpContext.Current.Response.Write("some string value")
antes de passar o seu gridview.
Outras dicas
Se você quiser exportar seu conteúdo para ExcelML verificar o RadGrid de Telerik
Você também pode inserir informações no cabeçalho para a rede etc
Aqui está o meu código para fazer o mesmo
protected void ExportExcel_OnClick(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=brugere.xls"); Response.Charset = "windows-1252"; Response.ContentType = "application/vnd.xls"; using (StringWriter stringWrite = new StringWriter()) using (HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite)) { GridView1.AllowPaging = false; GridView1.DataBind(); GridView1.RenderControl(htmlWrite); string html = stringWrite.ToString(); string result = Replacer.Replace(html, ""); Response.Write(result); } Response.End(); }
Observe que im corte resultante html usando uma expressão regular para evitar a formatação, imagens, divs e whatnots.
static readonly Regex Replacer = new Regex("(<input[^<>]*>)|"+ "(class=\"[^\"]*\")|(style=\"[^\"]*\")|"+ "(<a[^]*>)|(</a>)|(<div>)|(</div>)|" + "(cellspacing=\"[^\"]*\")|(cellpadding=\"[^\"]*\")|" + "(id=\"[^\"]*\")|(border=\"[^\"]*\")", RegexOptions.IgnoreCase);
Lembre-se de substituir o seguinte para garantir que grade irá processar fora de uma página
public override void VerifyRenderingInServerForm(Control control) { return; }
A abertura deste arquivo em Excel irá gerar uma mensagem de aviso. Gostaria de usar uma das bibliotecas de exportação open-source como NPOI. http://npoi.codeplex.com/
Se você ainda preferem usar a saída HTML, você pode considerar o download de documentação da Microsoft sobre o formato HTML do Office a partir deste link: http://msdn.microsoft.com/en-us /library/aa155477%28office.10%29.aspx
Você só precisa do arquivo CHM a partir deste arquivo (embalado em EXE).
Boa sorte.
Se o seu GridView é preenchido usando dados de um DataTable, DataSet ou List <>, em seguida, a seguinte biblioteca vai deixar você exportá-lo para um arquivo do Excel 2007 (.xlsx) simplesmente chamando um " CreateExcelDocument "função.
// Step 1: Create a DataSet, and put some sample data in it
DataSet ds = CreateSampleData();
// Step 2: Create the Excel .xlsx file
try
{
string excelFilename = "C:\\Sample.xlsx";
CreateExcelFile.CreateExcelDocument(ds, excelFilename);
}
catch (Exception ex)
{
MessageBox.Show("Couldn't create Excel file.\r\nException: " + ex.Message);
return;
}
O código fonte completo está disponível, para que você possa adaptá-lo, para adicionar suas linhas extras de dados, no topo de uma ou mais das planilhas.
Esta biblioteca usa Open XML bibliotecas, por isso é totalmente gratuito. http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm