문제

gridview를 Excel 스프레드 시트로 내보내는 가장 좋은 방법은 무엇입니까? 이것은 쉬운 것 같습니다

내 그리드 뷰에 내보내기 속성이 없다는 점을 제외하고. 이것을하는 가장 빠른 방법은 무엇입니까?

도움이 되었습니까?

해결책

Excel에 대한 내보내기에서 BtnexporttoExcel 클릭 이벤트 에이 코드를 작성하십시오.

    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 파일의 상단에있는 서식 옵션을 참조하는 방식입니다.

행운을 빕니다. 더 많은 설명이 필요하면 알려주세요.

편집하다:생성해야 할 필요한 XML에 대한 느낌을 얻으려면 템플릿 Excel 파일 만 한 번만 작성하면됩니다. 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 통합 문서를 생성하기 위해 간단한 객체 모델을 노출시킵니다.

그리드 뷰 컨트롤과 내장 된 통합은 없지만 일반 어댑터를 작성하는 것은 쉽고 다른 프로젝트에서는 재사용 할 수 있습니다.

이 방법은 서버에 또는 XML을 사용하여 XML을 설치하지 않고도 Excel 형식으로 바로 들어갑니다.

        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 그리고 모든 행을 통해. 유일한 것은 페이징을 허용하고 둘 이상의 페이지가 Pagesize를 높은 값으로 설정해야한다는 것입니다 (100000000으로 설정). DataBind 그만큼 GridView 다시하고 당신의 일을하십시오. 그 후 이전 페이지 크기 값을 다시 설정합니다. 누군가가 더 나은 솔루션을 알고 있다면 천만에요.

편집 : 시도/캐치는 어떤 이유로 컨트롤 유형을 확인한 다음 레이블 또는 레이블로 캐스트 할 수 없기 때문입니다. 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을 설치하고 프로젝트에서 Office Interop 라이브러리를 참조해야합니다. 추가하다:

Microsoft.Office.core를 가져 오기, Microsoft.Office.interop을 가져옵니다

위의 솔루션은 GridView를 가져 와서 HTML을 끌어냅니다. 그런 다음 탁월하게 씁니다. 그리드에서 나오는 HTML에는 패딩 및 색상과 같은 스타일 속성이 포함됩니다. 또한 정렬 가능한 열 제목을 링크처럼 보이게합니다. 내가 이것을 사용했을 때 나는 원치 않는 스타일을 벗기기 위해 사용자 정의 구문자를 썼다. 각 그리드에만 해당되므로 그 작업을 귀하에게 맡길 것입니다.

안에 코드가 없더라도 재정의를 확인하기 위해 재정의를 포함하는 것이 매우 중요합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top