2009-09-10 96 views
1

将gridview导出到Excel电子表格的最佳方式是什么? This seems easy导出gridview数据

除了我的Gridview没有导出属性。什么是最快的方法来做到这一点?

+0

这应该可能超过用户 – 2009-09-10 18:02:49

+1

我不同意,如果他想以编程方式做。我认为这是事实。 – 2009-09-10 18:13:52

+0

是布莱恩。我想以编程方式。 – Eric 2009-09-10 19:26:32

回答

1

在导出为ex​​cel时将此代码写入btnexporttoExcel Click事件。

string attachment = "attachment; filename=Export.xls"; 

    Response.ClearContent(); 

    Response.AddHeader("content-disposition", attachment); 

    Response.ContentType = "application/ms-excel"; 

    StringWriter sw = new StringWriter(); 

    HtmlTextWriter htw = new HtmlTextWriter(sw); 

    // Create a form to contain the grid 

    HtmlForm frm = new HtmlForm(); 

    gv.Parent.Controls.Add(frm); 

    frm.Attributes["runat"] = "server"; 

    frm.Controls.Add(gv); 

    frm.RenderControl(htw); 



    //GridView1.RenderControl(htw); 

    Response.Write(sw.ToString()); 

    Response.End(); 
0

This library for .net在我们的使用案例中工作得非常好。

该库允许您使用XML生成Excel工作簿,它在C#中100%构建,并且不需要安装Excel来生成文件。它公开了一个简单的对象模型来生成XML工作簿。

没有与GridView控件的内置集成,但是编写通用适配器非常简单,并且可以在其他项目中重用。

1

这里可能有些东西,但是如果你想自己做,你可以编写一些代码,它们遍历GridView.Rows集合,然后是GridViewRow.Cells集合。

从那里建立一个CSV文件应该很容易,而且Excel可以读取它没有问题。

CSV文件只是包含引号内的值的文本文件,用逗号分隔。像这样:

"value", "value", "value" 
"value", "value", "value" 

您可以弹出记事本打开并手动构建一个试用它。

-1
Private exportToExcel As Boolean = False 

Private Sub LoadInExcel() 
    Me.Response.ClearContent() 
    Me.Response.AddHeader("content-disposition", "attachment; filename=MyFile.xls") 
    Me.Response.ContentType = "application/ms-excel" 
    Dim sw1 As New IO.StringWriter 
    Dim htw1 As HtmlTextWriter = New HtmlTextWriter(sw1) 
    GridView1.RenderControl(htw1) 
    Response.Write(sw1.ToString()) 
    Response.End() 
End Sub 

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control) 
    ' Confirms that an HtmlForm control is rendered for the specified ASP.NET 
    ' server control at run time. 
End Sub 

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter) 
    If exportToExcel Then 
     LoadInExcel() 
    End If 

    MyBase.Render(writer) 
End Sub 

Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click 
    exportToExcel = True 
End Sub 

您必须安装excel并参考项目中的Office互操作库。 地址:

进口Microsoft.Office.Core, 进口Microsoft.Office.Interop

上述该解决方案利用GridView和拉HTML出来。然后写入excel。来自网格的html将包含样式属性,如填充颜色&。它也会使可排序的列标题看起来像链接。当我使用这个时,我写了一个自定义解析器去除所有不需要的样式,只给出原始数据。我将把这个任务交给你,因为它是针对每个网格的。

即使内部没有任何代码,将重写包括到VerifyRenderingInServerForm中也是非常重要的。

+0

我喜欢你要去的地方。但是,我不允许导入microsoft.office.core – Eric 2009-09-10 19:22:31

+0

我可以在哪里获取Microsoft Office文件? – Eric 2009-09-10 19:47:33

+0

@Eric - 您可以通过将Office安装在同一台计算机上来获取它们。但是,应该指出的是,在服务器上运行Office通常不被认为是最佳实践。 – rjzii 2009-09-11 14:44:28

1

我已经做了好几次了。 Excel有一个XML版本。它以.xml扩展名结尾,但您可以将文件的扩展名更改为.xls,并且XML格式的文件将在Excel中打开。

这种方法最大的障碍是excel XML格式。我通常以我想要的大致格式在excel中创建一个excel文件。然后将Excel文件保存为XML格式,然后在文本编辑器中打开它。

我通常从这个Excel示例页面创建一个模板文件。然后,当我在Gridview中导出信息时,我只需要为包含我计划填充的单元格的部分创建xml,我只是预先添加并追加模板文件中已有的文本。

一旦你打开了格式化的Excel文件中的XML,你就会比较容易地找出所需要的XML。要理解的最难的部分是单元格引用格式化选项的方式,它们位于XML文件的顶部。

祝你好运,让我知道,如果你需要进一步澄清。

编辑: 您只需要创建模板excel文件一次,只是为了获得所需的XML,你需要生成一个感觉。一旦你生成XML使用下面的代码将其发送给用户:

string fileName = "ExportedFile.xls"; 
Response.Clear(); 
Response.Buffer = true; 
Response.ContentType = "text/xml"; 
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); 
ExportToExcel(HttpContext.Current.Response.OutputStream, testUID); 
Response.End(); 



public static void ExportToExcel(Stream outputStream) 
{ 
    XmlTextWriter xmlSink = new XmlTextWriter(outputStream, Encoding.Default); 

    //ExcelHeaderString and ExcelStylesString are from the template 
    xmlSink.WriteRaw(ExcelHeaderString); 
    xmlSink.WriteRaw(ExcelStylesString); 

    //write your elements here 
    xmlSink.WriteElement("YourElements"); 

    //ExcelFooterString is from the template 
    xmlSink.WriteRaw(ExcelFooterString); 
} 
+0

我的问题是,我必须在每台机器上都这么做吗?我必须在每台机器上创建一个excel文件。这是应用程序将在公司范围内使用。 – Eric 2009-09-10 19:39:04

+0

我以为你会将它编入包含GridView的代码中。我对你的陈述有些困惑。你正在创建一个基于Web的应用程序或桌面应用程序吗? – Chris 2009-09-10 19:42:17

+0

是的。那是对的。我将尝试对此进行编程。这是一个基于网络的应用程序。我可能是一个迷茫的人。但你说过你必须通常在Excel中创建一个excel文件。我必须在每台使用此应用程序的计算机上都这样做? – Eric 2009-09-10 19:50:59

0

我用CarlosAg.ExcelXmlWriterlink

我经历了所有GridViewsHeaderCells然后通过所有行。唯一的一点是,如果你允许分页和你已经超过一个页面,你必须设置每页为高值(我设置为10000000),然后DataBindGridView一次做你的工作。之后设置旧的PageSize值。如果有人知道更好的解决方案,欢迎您。

编辑:try/catch语句是有因为某种原因,它是不可能的检查控制类型,然后转换为标签或LinkButton ==> control.GetType()

这是我的代码。

public static Workbook CreateWorkbook(GridView gridView) 
    { 
     int pageSize = gridView.PageSize; 
     gridView.PageSize = 10000000; 
     gridView.DataBind(); 

     Workbook workbook = new Workbook(); 
     Worksheet sheet = workbook.Worksheets.Add("Export"); 

     WorksheetStyle style = workbook.Styles.Add("headerStyle"); 
     style.Font.Bold = true; 
     style = workbook.Styles.Add("defaultStyle"); 
     style.Alignment.WrapText = true; 
     style = workbook.Styles.Add("infoStyle"); 
     style.Font.Color = "Red"; 
     style.Font.Bold = true; 

     sheet.Table.Rows.Add(new WorksheetRow()); 

     WorksheetRow headerRow = new WorksheetRow(); 
     foreach (DataControlFieldHeaderCell cell in gridView.HeaderRow.Cells) 
     { 
      if (!string.IsNullOrEmpty(cell.Text)) 
       headerRow.Cells.Add(cell.Text, DataType.String, "headerStyle"); 
      else 
       foreach (Control control in cell.Controls) 
       { 
        LinkButton linkButton = new LinkButton(); 
        try 
        { 
         linkButton = (LinkButton)control; 
        } 
        catch { } 

        if (!string.IsNullOrEmpty(linkButton.Text)) 
         headerRow.Cells.Add(linkButton.Text, DataType.String, "headerStyle"); 
        else 
        { 
         Label label = new Label(); 
         try 
         { 
          label = (Label)control; 
         } 
         catch { } 
         if (!string.IsNullOrEmpty(label.Text)) 
          headerRow.Cells.Add(label.Text, DataType.String, "headerStyle"); 
        } 
       } 
     } 

     sheet.Table.Rows.Add(headerRow); 

     foreach (GridViewRow row in gridView.Rows) 
     { 
      WorksheetRow wrow = new WorksheetRow(); 
      foreach (TableCell cell in row.Cells) 
      { 
       foreach (Control control in cell.Controls) 
       { 
        if (control.GetType() == typeof(Label)) 
        { 
         wrow.Cells.Add(((Label)control).Text, DataType.String, "defaultStyle"); 
        } 
       } 
      } 
      sheet.Table.Rows.Add(wrow); 
     } 

     gridView.PageSize = pageSize; 

     return workbook; 
    } 
0

此方法直接转换为Excel格式,无需在服务器上安装XML或使用XML。

 Protected Sub ExportToExcel() 

     Dim gv1 As GridView = FindControlRecursive(objPlaceHolder, "GridView1") 
     If Not gv1 Is Nothing Then 
      Response.ClearHeaders() 
      Response.ClearContent() 

      ' Set the content type to Excel 
      Response.ContentType = "application/vnd.ms-excel" 

      ' make it open the save as dialog 
      Response.AddHeader("content-disposition", "attachment; filename=ExcelExport.xls") 

      'Turn off the view state 
      Me.EnableViewState = False 

      'Remove the charset from the Content-Type header 
      Response.Charset = String.Empty 

      Dim myTextWriter As New System.IO.StringWriter 
      Dim myHtmlTextWriter As New System.Web.UI.HtmlTextWriter(myTextWriter) 
      Dim frm As HtmlForm = New HtmlForm() 
      Controls.Add(frm) 
      frm.Controls.Add(gv1) 

      'Get the HTML for the control 
      frm.RenderControl(myHtmlTextWriter) 

      'Write the HTML to the browser 
      Response.Write(myTextWriter.ToString()) 
      'End the response 
      Response.End() 
     End If 
    End Sub 

Private Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control 
    If root.ID = id Then 
     Return root 
    End If 
    Dim c As Control 
    For Each c In root.Controls 
     Dim t As Control = FindControlRecursive(c, id) 
     If Not t Is Nothing Then 
      Return t 
     End If 
    Next 
    Return Nothing 
End Function