如何在vb.net中导出gridview后减轻Excel工作簿的权重

时间:2016-02-03 10:58:38

标签: .net vb.net excel gridview

我使用以下代码在Excel中导出gridview:

 Protected Sub ExportToExcel(sender As Object, e As EventArgs) Handles ExportExcel.Click
        Try
            Response.Clear()
            Response.Buffer = True
            Response.AddHeader("content-disposition", "attachment;filename=ExportEthias.xls")
            Response.Charset = ""
            Response.ContentType = "application/vnd.ms-excel"
            Using sw As New StringWriter()
                Dim hw As New HtmlTextWriter(sw)

                GvActifs.BackColor = Color.White
                For Each cell As TableCell In GvActifs.HeaderRow.Cells
                    cell.BackColor = Color.DarkBlue
                    cell.BorderStyle = BorderStyle.Solid
                    cell.ForeColor = Color.White
                Next
                For Each row As GridViewRow In GvActifs.Rows
                    row.BackColor = Color.White
                    For Each cell As TableCell In row.Cells
                        If row.RowIndex Mod 2 = 0 Then
                            cell.BackColor = GvActifs.AlternatingRowStyle.BackColor

                        Else
                            cell.BackColor = GvActifs.RowStyle.BackColor
                        End If
                        cell.CssClass = "textmode"
                        cell.BorderStyle = BorderStyle.Solid
                    Next
                Next

                GvActifs.RenderControl(hw)
                'Le format de base est le texte pour éviter les problèmes d'arrondis des nombres
                Dim style As String = "<style> .textmode { } </style>"
                Response.Write(style)
                Response.Output.Write(sw.ToString())
                Response.Flush()
                Response.End()
            End Using
        Catch ex As Exception
            lblMessage.Text = "Erreur export Excel : " & ex.Message
        End Try
    End Sub
    Public Overrides Sub VerifyRenderingInServerForm(control As Control)
        ' Verifies that the control is rendered
    End Sub

它工作正常,但Excel为5k行做了14,7 MB。它很多:) 如何减轻Excel中导出的权重?

提前致谢。

1 个答案:

答案 0 :(得分:1)

我发现当您进行大量格式化时,Excel文件会膨胀。即使您稍后删除格式(颜色,字体),它也会使文件大小变大。我看到你正在格式化单个单元格。如果您设法以可以同时格式化一系列单元格的方式编写代码,则文件大小将大大减少。这是因为这(伪代码):

Cell A1: Bold Cell A2: Bold Cell A3: Bold ... Cell Z3: Bold

在文件中存储的空间比:

要多得多

Range A1-Z5: Bold

在代码的这一部分:

If row.RowIndex Mod 2 = 0 Then
  cell.BackColor = GvActifs.AlternatingRowStyle.BackColor
Else

您正在着色每个单独的单元格,即使您所做的只是交替行颜色。那么为什么不改变行的颜色呢?

HTH!