什么是最好的方式,以出口内纳入一个Excel电子表格? 这一似乎很容易

除了我的内没有一个出口的属性。什么是最快的方式这样做吗?

有帮助吗?

解决方案

导出到Excel中将此代码写入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();

其他提示

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

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

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

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

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

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

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

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

打开xml格式的excel文件后,您将相对容易地找出所需的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);
}

.net的这个库对我们的用例非常有效。

  

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

没有与GridView控件的内置集成,但编写通用适配器很容易,并且可以在其他项目中重复使用。

此方法直接进入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

我用 CarlosAg.ExcelXmlWriter 链接.

我循环通过的所有 GridViews HeaderCells 然后通过的所有行。唯一的事情是,如果你允许寻呼你已经超过一页你得设置页大小的高值(I设10000000)然后 DataBindGridView 再做你的工作。事后设定的老页大小值回。如果有人知道一个更好的解决方案,你是受欢迎的。

编辑:Try/赶上是存在的,因为由于某种原因,这是不可能的检查控制的类型,然后转换为标签或 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;
    }
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和参照办事处的互操作的图书馆项目。添加:

进口Microsoft。办公室。核心, 进口Microsoft。办公室。互操作

解决上述需要的内和拉html出的。然后把它写到excel。Html来自格将包括风格的属性,例如填料和颜色。它也将让排序列标题看起来像链接。当我用这个,我写了一定的分析器来去除所有不必要的造型出来给我的只是原始的数据。我会离开,任务给你,因为它是具体到每一个电网。

这是非常重要的,包括复盖到VerifyRenderingInServerForm,即使没有任何代码内。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top