导出到 Excel

发布于 2024-07-15 11:16:59 字数 2002 浏览 5 评论 0原文

我想将 GridView 导出到 Excel,这很容易。 但在 Excel 中的网格上方,我想要一些其他信息用于识别。 我可以以某种方式导出网格视图以外的东西,然后放入下面的网格视图吗?

编辑: 由于某种原因,当 GridView1 可见并且我尝试导出时,整个页面都会导出,而不仅仅是 gridview。 不知道为什么!

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

I would like to export a GridView to excel, which is easy enough. But above the grid, in Excel, I would like some other information for identification. Can I somehow export things other than gridviews while then putting in the gridview below?

Edit:
For some reason when the GridView1 is visible and I try to export, the entire page exports and not just the gridview. Not sure why!

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

奶气 2024-07-22 11:16:59

是的你可以。

做这样的事情:

HttpContext.Current.Response.Write("some string value")

在传递 gridview 之前。

Yes you can.

Do something like this:

HttpContext.Current.Response.Write("some string value")

before you pass your gridview.

倾听心声的旋律 2024-07-22 11:16:59

如果您想将内容导出到 ExcelML,请查看 Telerik 的 RadGrid

您还可以将标题信息插入网格等

If you want to export your content to ExcelML check out the RadGrid from Telerik

You can also insert header info into the grid etc

新一帅帅 2024-07-22 11:16:59

这是我执行相同操作的代码,

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();
}

请注意,我使用正则表达式修剪生成的 html,以避免格式化、图像、div 等。

static readonly Regex Replacer = new Regex("(<input[^<>]*>)|"+
  "(class=\"[^\"]*\")|(style=\"[^\"]*\")|"+
  "(<a[^]*>)|(</a>)|(<div>)|(</div>)|" +
  "(cellspacing=\"[^\"]*\")|(cellpadding=\"[^\"]*\")|" +
  "(id=\"[^\"]*\")|(border=\"[^\"]*\")", RegexOptions.IgnoreCase);

请记住覆盖以下内容以确保网格将在页面外部呈现

public override void VerifyRenderingInServerForm(Control control) {
    return; 
}

Here is my code for doing the same

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();
}

Notice that im trimming the resulting html using a regular expression to avoid formatting, images, divs and whatnots.

static readonly Regex Replacer = new Regex("(<input[^<>]*>)|"+
  "(class=\"[^\"]*\")|(style=\"[^\"]*\")|"+
  "(<a[^]*>)|(</a>)|(<div>)|(</div>)|" +
  "(cellspacing=\"[^\"]*\")|(cellpadding=\"[^\"]*\")|" +
  "(id=\"[^\"]*\")|(border=\"[^\"]*\")", RegexOptions.IgnoreCase);

Remember to override the following to ensure that grid will render outside a Page

public override void VerifyRenderingInServerForm(Control control) {
    return; 
}
黄昏下泛黄的笔记 2024-07-22 11:16:59

在 Excel 中打开此文件将生成一条警告消息。 我会使用 NPOI 等开源导出库之一。
http://npoi.codeplex.com/

如果您仍然喜欢使用 HTML 输出,您可以考虑下载Microsoft 关于 Office HTML 格式的文档来自此链接:
http://msdn.microsoft.com/en-us /library/aa155477%28office.10%29.aspx

您只需要此存档中的 CHM 文件(打包在 EXE 中)。

祝你好运。

Opening this file in Excel will generate a warning message. I would use one of the open-source export libraries like NPOI.
http://npoi.codeplex.com/

If you still prefer to use the HTML output, you may consider downloading Microsoft's documentation on the Office HTML format from this link:
http://msdn.microsoft.com/en-us/library/aa155477%28office.10%29.aspx

You only need the CHM file from this archive (packed in EXE).

Good luck.

肥爪爪 2024-07-22 11:16:59

如果您的 GridView 使用 DataTable、DataSet 或 List<> 中的数据填充 那么下面的库将让您只需调用一个“CreateExcelDocument”函数即可将其导出到 Excel 2007 (.xlsx) 文件。

// 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;
}

提供了完整的源代码,因此您可以对其进行调整,以在一个或多个工作表的顶部添加额外的数据行。

该库使用Open XML库,因此它是完全免费的。
http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

If your GridView is filled using data from a DataTable, DataSet or List<> then the following library will let you export it to an Excel 2007 (.xlsx) file simply by calling one "CreateExcelDocument" function.

// 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;
}

The full source code is provided, so you could adapt it, to add your extra rows of data, at the top of one or more of the worksheets.

This library uses the Open XML libraries, so it's completely free.
http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文