문제

ASP.NET 앱 (vb.net CodeBehind)에 섹션을 추가하려고하여 사용자가 데이터베이스 데이터를 기반으로 생성 할 데이터를 Excel 파일로 가져올 수 있습니다. 이 작업을 수행하는 방법에는 여러 가지가 있지만 각각의 단점이 있습니다. 어떻게 데이터를 반환 하시겠습니까? 나는 가능한 한 깨끗하고 간단한 것을 찾고 있습니다.

도움이 되었습니까?

해결책

CSV

장점 :

  • 단순한

단점 :

  • 다른 로케일 또는 다른 Excel 구성에서는 작동하지 않을 수 있습니다 (즉, 분리기 목록).
  • 서식, 공식 등을 적용 할 수 없습니다

HTML

장점 :

  • 여전히 매우 간단합니다
  • 간단한 서식 및 공식을 지원합니다

단점 :

  • 파일의 이름을 XLS로 지정해야하며 Excel은 네이티브 Excel 파일을 여는 것에 대해 경고 할 수 있습니다.
  • 통합 문서 당 하나의 워크 시트

OpenXML (Office 2007 .XLSX)

장점 :

  • 기본 Excel 형식
  • 모든 Excel 기능을 지원합니다
  • 하지 마라 필요하다 Excel의 설치 사본
  • 피벗 테이블을 생성 할 수 있습니다
  • 오픈 소스 프로젝트를 사용하여 생성 할 수 있습니다 epplus

단점 :

  • Excel 2007 이외의 제한된 호환성 (요즘에는 문제가되지 않아야합니다)
  • 타사 구성 요소를 사용하지 않는 한 복잡합니다

스프레드 시트ml (오픈 형식 XML)

장점 :

  • 기본 Excel 형식에 비해 간단합니다
  • 대부분의 엑셀 기능 지원 : 서식, 스타일, 공식, 통합 문서 당 여러 시트
  • Excel을 사용하기 위해 설치할 필요가 없습니다.
  • 타사 라이브러리가 필요하지 않음 - XML을 작성하십시오.
  • 문서는 Excel XP/2003/2007에서 열 수 있습니다.

단점 :

  • 좋은 문서의 부족
  • 이전 버전의 Excel에서 지원되지 않음 (2000 년 이전)
  • 쓰기 전용, 일단 당신이 그것을 열고 Excel에서 변경하면 기본 Excel로 변환됩니다.

XLS (타사 구성 요소에 의해 생성)

장점 :

  • 모든 형성, 공식 등으로 기본 Excel 파일을 생성합니다.

단점 :

  • 비용
  • 종속성을 추가하십시오

com interop

장점 :

  • 기본 Microsoft 라이브러리를 사용합니다
  • 기본 문서에 대한 지원을 읽으십시오

단점 :

  • 아주 느린
  • 종속성/버전 일치 문제
  • 읽을 때 웹 사용을위한 동시/데이터 무결성 문제
  • 아주 느린
  • 웹 사용에 대한 스케일링 문제 (동시성과 다름) : 서버에서 많은 Excel 앱 인스턴스를 생성해야합니다.
  • Windows가 필요합니다
  • 느린다 고 언급 했습니까?

다른 팁

HTML 테이블 셀로 데이터를 출력 할 수 있습니다. .xls 또는 .xlsx 그것에 대한 확장 및 Excel은 마치 기본 문서 인 것처럼 열 것입니다. 이러한 방식으로 제한된 형식 및 공식 계산을 수행 할 수도 있으므로 CSV보다 훨씬 강력합니다. 또한 HTML 테이블을 출력하는 것은 asp.net과 같은 웹 플랫폼에서 쉽게 수행 할 수 있어야합니다.)

Excel 통합 문서 내에 여러 워크 시트 또는 이름이 지정된 워크 시트가 필요한 경우 XML 스키마를 통해 유사한 작업을 수행 할 수 있습니다. SpreadSheetML. 이것은 ~ 아니다 Office 2007과 함께 배송 된 새로운 형식이지만 Excel 2000만큼 멀리 작동하는 완전히 다른 것입니다. 작동 방식을 설명하는 가장 쉬운 방법은 예제입니다.

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?> 
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
        xmlns:o="urn:schemas-microsoft-com:office:office"
        xmlns:x="urn:schemas-microsoft-com:office:excel"
        xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
        xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
      <Author>Your_name_here</Author>
      <LastAuthor>Your_name_here</LastAuthor>
      <Created>20080625</Created>
      <Company>ABC Inc</Company>
      <Version>10.2625</Version>
</DocumentProperties>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
        <WindowHeight>6135</WindowHeight>
        <WindowWidth>8445</WindowWidth>
        <WindowTopX>240</WindowTopX>
        <WindowTopY>120</WindowTopY>
        <ProtectStructure>False</ProtectStructure>
        <ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>

<Styles>
      <Style ss:ID="Default" ss:Name="Normal">
            <Alignment ss:Vertical="Bottom" />
            <Borders />
            <Font />
            <Interior />
            <NumberFormat />
            <Protection />
      </Style>
</Styles>

<Worksheet ss:Name="Sample Sheet 1">
<Table ss:ExpandedColumnCount="2" x:FullColumns="1" x:FullRows="1" ID="Table1">
<Column ss:Width="150" />
<Column ss:Width="200" />
<Row>
      <Cell><Data ss:Type="Number">1</Data></Cell>
      <Cell><Data ss:Type="Number">2</Data></Cell>
</Row>
<Row>
      <Cell><Data ss:Type="Number">3</Data></Cell>
      <Cell><Data ss:Type="Number">4</Data></Cell>
</Row>
<Row>
      <Cell><Data ss:Type="Number">5</Data></Cell>
      <Cell><Data ss:Type="Number">6</Data></Cell>
</Row>
<Row>
      <Cell><Data ss:Type="Number">7</Data></Cell>
      <Cell><Data ss:Type="Number">8</Data></Cell>
</Row>
</Table>
</Worksheet>

<Worksheet ss:Name="Sample Sheet 2">
<Table ss:ExpandedColumnCount="2" x:FullColumns="1" x:FullRows="1" ID="Table2">
<Column ss:Width="150" />
<Column ss:Width="200" />
<Row>
      <Cell><Data ss:Type="String">A</Data></Cell>
      <Cell><Data ss:Type="String">B</Data></Cell>
</Row>
<Row>
      <Cell><Data ss:Type="String">C</Data></Cell>
      <Cell><Data ss:Type="String">D</Data></Cell>
</Row>
<Row>
      <Cell><Data ss:Type="String">E</Data></Cell>
      <Cell><Data ss:Type="String">F</Data></Cell>
</Row>
<Row>
      <Cell><Data ss:Type="String">G</Data></Cell>
      <Cell><Data ss:Type="String">H</Data></Cell>
</Row>
</Table>
</Worksheet>
</Workbook> 

a에서 오는 경우 데이터 가능:

public static void DataTabletoXLS(DataTable DT, string fileName)
{
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.Charset = "utf-16";
    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
    HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName));
    HttpContext.Current.Response.ContentType = "application/ms-excel";

    string tab = "";
    foreach (DataColumn dc in DT.Columns)
    {
        HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace("\n", "").Replace("\t", ""));
        tab = "\t";
    }
    HttpContext.Current.Response.Write("\n");

    int i;
    foreach (DataRow dr in DT.Rows)
    {
        tab = "";
        for (i = 0; i < DT.Columns.Count; i++)
        {
            HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace("\n", "").Replace("\t", ""));
            tab = "\t";
        }
        HttpContext.Current.Response.Write("\n");
    }
    HttpContext.Current.Response.End();
}

a 그리드 뷰:

public static void GridviewtoXLS(GridView gv, string fileName)
{
    int DirtyBit = 0;
    int PageSize = 0;
    if (gv.AllowPaging == true)
    {
        DirtyBit = 1;
        PageSize = gv.PageSize;
        gv.AllowPaging = false;
        gv.DataBind();
    }

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.Charset = "utf-8";
    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
    HttpContext.Current.Response.AddHeader(
        "content-disposition", string.Format("attachment; filename={0}.xls", fileName));
    HttpContext.Current.Response.ContentType = "application/ms-excel";

    using (StringWriter sw = new StringWriter())
    using (HtmlTextWriter htw = new HtmlTextWriter(sw))
    {
        //  Create a table to contain the grid
        Table table = new Table();

        //  include the gridline settings
        table.GridLines = gv.GridLines;

        //  add the header row to the table
        if (gv.HeaderRow != null)
        {
            Utilities.Export.PrepareControlForExport(gv.HeaderRow);
            table.Rows.Add(gv.HeaderRow);
        }

        //  add each of the data rows to the table
        foreach (GridViewRow row in gv.Rows)
        {
            Utilities.Export.PrepareControlForExport(row);
            table.Rows.Add(row);
        }

        //  add the footer row to the table
        if (gv.FooterRow != null)
        {
            Utilities.Export.PrepareControlForExport(gv.FooterRow);
            table.Rows.Add(gv.FooterRow);
        }

        //  render the table into the htmlwriter
        table.RenderControl(htw);

        //  render the htmlwriter into the response
        HttpContext.Current.Response.Write(sw.ToString().Replace("£", ""));
        HttpContext.Current.Response.End();
    }

    if (DirtyBit == 1)
    {
        gv.PageSize = PageSize;
        gv.AllowPaging = true;
        gv.DataBind();
    }
}

private static void PrepareControlForExport(Control control)
{
    for (int i = 0; i < control.Controls.Count; i++)
    {
        Control current = control.Controls[i];
        if (current is LinkButton)
        {
            control.Controls.Remove(current);
            control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
        }
        else if (current is ImageButton)
        {
            control.Controls.Remove(current);
            control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
        }
        else if (current is HyperLink)
        {
            control.Controls.Remove(current);
            control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
        }
        else if (current is DropDownList)
        {
            control.Controls.Remove(current);
            control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
        }
        else if (current is CheckBox)
        {
            control.Controls.Remove(current);
            control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
        }

        if (current.HasControls())
        {
            Utilities.Export.PrepareControlForExport(current);
        }
    }
}

이것은 SpreadML 주변의 무료 래퍼입니다. 훌륭하게 작동합니다.

http://www.carlosag.net/tools/excelxmlwriter/

주어진 답변과 동료와의 상담을 바탕으로 최상의 솔루션은 XML 파일 또는 HTML 테이블을 생성하여 첨부 파일로 누르는 것 같습니다. 동료가 권장하는 한 가지 변경 사항은 데이터 (즉, HTML 테이블)가 응답 객체에 직접 쓸 수 있으므로 파일을 작성할 필요가 없어 권한 문제로 인해 문제가 될 수있는 파일을 제거 할 필요가 없다는 것입니다. 경합 및 예정된 제거가 발생하도록 보장합니다.

코드의 스 니펫은 다음과 같습니다. 아직 확인하지 않았으며 모든 코드를 모두 제공하지는 않았지만 아이디어를 잘 나타내는 것 같습니다.

    Dim uiTable As HtmlTable = GetUiTable(groupedSumData)

    Response.Clear()

    Response.ContentType = "application/vnd.ms-excel"
    Response.AddHeader("Content-Disposition", String.Format("inline; filename=OSSummery{0:ddmmssf}.xls", DateTime.Now))

    Dim writer As New System.IO.StringWriter()
    Dim htmlWriter As New HtmlTextWriter(writer)
    uiTable.RenderControl(htmlWriter)
    Response.Write(writer.ToString)

    Response.End()

Excel은 HTML을 이해하므로 .xls 확장자가있는 임시 파일에 HTML 테이블로 데이터를 작성하고 파일의 FileInfo를 가져오고 사용하여 다시 날려 버릴 수 있습니다.

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fi.Name);
Response.AddHeader("Content-Length", fi.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(fi.FullName);
Response.End();

임시 파일을 피하려면 writefile을 사용하는 대신 메모리 스트림에 글을 쓰고 바이트를 다시 쓸 수 있습니다.

콘텐츠 길이 헤더가 생략되면 HTML을 직접 다시 쓸 수 있지만 모든 브라우저에서 항상 제대로 작동하지 않을 수 있습니다.

나는 개인적으로 XML 방법을 선호합니다. 데이터 세트의 데이터베이스에서 데이터를 반환하고 XML에 저장 한 다음 적절한 문서를 형식화하는 변환 규칙이 포함 된 XSLT 파일을 작성하고 간단한 XML 변환이 작업을 완료합니다. 이것의 가장 중요한 부분은 셀 포맷, 조건부 서식을 수행하고, 헤더 및 바닥 글을 설정하고, 인쇄 범위를 설정할 수 있습니다.

나는 이것을 두 번했고 가장 쉬운 방법은 단순히 CSV (Comma 분리 값) 파일을 반환하는 것이 었습니다. Excel은 완벽하게 가져 오며 비교적 빠릅니다.

우리는 데이터를 데이터를 내보내고 항상 탁월합니다. HTML로 변환 한 다음 Excel 파일로 작성

Response.ContentType = "application/vnd.ms-excel"
    Response.Charset = ""
    Response.AddHeader("content-disposition", "fileattachment;filename=YOURFILENAME.xls")
    Me.EnableViewState = False
    Dim sw As System.IO.StringWriter = New System.IO.StringWriter
    Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
    ClearControls(grid)
    grid.RenderControl(hw)
    Response.Write(sw.ToString())
    Response.End()

이 방법을 가진 유일한 Gotcha는 많은 그리드에 버튼이나 링크가 있으므로 다음에도 필요하다는 것입니다.

'needed to export grid to excel to remove link button control and represent as text
Private Sub ClearControls(ByVal control As Control)
    Dim i As Integer
    For i = control.Controls.Count - 1 To 0 Step -1
        ClearControls(control.Controls(i))
    Next i

    If TypeOf control Is System.Web.UI.WebControls.Image Then
        control.Parent.Controls.Remove(control)
    End If

    If (Not TypeOf control Is TableCell) Then
        If Not (control.GetType().GetProperty("SelectedItem") Is Nothing) Then
            Dim literal As New LiteralControl
            control.Parent.Controls.Add(literal)
            Try
                literal.Text = CStr(control.GetType().GetProperty("SelectedItem").GetValue(control, Nothing))
            Catch
            End Try
            control.Parent.Controls.Remove(control)
        Else
            If Not (control.GetType().GetProperty("Text") Is Nothing) Then
                Dim literal As New LiteralControl
                control.Parent.Controls.Add(literal)
                literal.Text = CStr(control.GetType().GetProperty("Text").GetValue(control, Nothing))
                control.Parent.Controls.Remove(control)
            End If
        End If
    End If
    Return
End Sub

나는 어딘가에 잘 작동한다는 것을 알았습니다.

추천합니다 무료 OpenSource Excel Generation Libruary OpenXML을 기반으로합니다

몇 달 전에 도움이되었습니다.

저장된 절차에서 가져 오는 보고서가 있습니다. 결과는 Excel로 내보내집니다. 그것은 ado.net 대신 ado를 사용하고 그 이유는이 라인 인 이유입니다.

oSheet.Cells(2, 1).copyfromrecordset(rst1)

대부분의 작업을 수행하며 Ado.net에서는 사용할 수 없습니다.

‘Calls stored proc in SQL Server 2000 and puts data in Excel and ‘formats it

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim cnn As ADODB.Connection
        cnn = New ADODB.Connection
        cnn.Open("Provider=SQLOLEDB;data source=xxxxxxx;" & _
          "database=xxxxxxxx;Trusted_Connection=yes;")

        Dim cmd As New ADODB.Command


        cmd.ActiveConnection = cnn


        cmd.CommandText = "[sp_TomTepley]"
        cmd.CommandType = ADODB.CommandTypeEnum.adCmdStoredProc
        cmd.CommandTimeout = 0
        cmd.Parameters.Refresh()


        Dim rst1 As ADODB.Recordset
        rst1 = New ADODB.Recordset
        rst1.Open(cmd)

        Dim oXL As New Excel.Application
        Dim oWB As Excel.Workbook
        Dim oSheet As Excel.Worksheet

        'oXL = CreateObject("excel.application")
        oXL.Visible = True
        oWB = oXL.Workbooks.Add
        oSheet = oWB.ActiveSheet

        Dim Column As Integer
        Column = 1

        Dim fld As ADODB.Field
        For Each fld In rst1.Fields

            oXL.Workbooks(1).Worksheets(1).Cells(1, Column).Value = fld.Name
            oXL.Workbooks(1).Worksheets(1).cells(1, Column).Interior.ColorIndex = 15
            Column = Column + 1

        Next fld

        oXL.Workbooks(1).Worksheets(1).name = "Tom Tepley Report"
        oSheet.Cells(2, 1).copyfromrecordset(rst1)
        oXL.Workbooks(1).Worksheets(1).Cells.EntireColumn.AutoFit()


        oXL.Visible = True
        oXL.UserControl = True

        rst1 = Nothing

        cnn.Close()
        Beep()

    End Sub

GridView를 데이터로 채우면이 기능을 사용하여 HTML 형식의 데이터를 가져올 수 있지만 브라우저를 나타내면 Excel 파일임을 나타냅니다.

 Public Sub ExportToExcel(ByVal fileName As String, ByVal gv As GridView)

        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
        HttpContext.Current.Response.ContentType = "application/ms-excel"

        Dim sw As StringWriter = New StringWriter
        Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
        Dim table As Table = New Table

        table.GridLines = gv.GridLines

        If (Not (gv.HeaderRow) Is Nothing) Then
            PrepareControlForExport(gv.HeaderRow)
            table.Rows.Add(gv.HeaderRow)
        End If

        For Each row As GridViewRow In gv.Rows
            PrepareControlForExport(row)
            table.Rows.Add(row)
        Next

        If (Not (gv.FooterRow) Is Nothing) Then
            PrepareControlForExport(gv.FooterRow)
            table.Rows.Add(gv.FooterRow)
        End If

        table.RenderControl(htw)

        HttpContext.Current.Response.Write(sw.ToString)
        HttpContext.Current.Response.End()

    End Sub


    Private Sub PrepareControlForExport(ByVal control As Control)

        Dim i As Integer = 0

        Do While (i < control.Controls.Count)

            Dim current As Control = control.Controls(i)

            If (TypeOf current Is LinkButton) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))

            ElseIf (TypeOf current Is ImageButton) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))

            ElseIf (TypeOf current Is HyperLink) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))

            ElseIf (TypeOf current Is DropDownList) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))

            ElseIf (TypeOf current Is CheckBox) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))

            End If

            If current.HasControls Then
                PrepareControlForExport(current)
            End If

            i = i + 1

        Loop

    End Sub

Microsoft.Office.interop 네임 스페이스를 통해 COM Interop을 피하십시오. 너무 느리고 신뢰할 수없고 비평 할 수 없습니다. 마조히스트에는 적용 할 수 없습니다.

이 라이브러리를 사용하여 멋지게 포맷 된 Excel 파일을 만들 수 있습니다. http://officehelper.codeplex.com/documentation.

Microsoft Office는 웹 서버에 설치할 필요가 없습니다!

CSV가 가장 쉬운 방법입니다. 대부분의 경우 Excel에 연결됩니다. 그렇지 않으면 자동화 API 또는 XML 형식을 사용해야합니다. API 및 XML은 사용하기 어렵지 않습니다.

Excel 용 XML 생성에 대한 정보

CSV 경로 (위에서 설명한대로) 또는 요즘에는 자주 파일을 생성하기 위해 Infragistics NetAdvantage를 사용합니다. (Infragistics가 진행되는 대부분의 시간은 기존의 Ultrawebgrid를 내보내는 것만으로도 추가 형식 조정이 필요하지 않으면 본질적으로 1-Loc 솔루션입니다. Excel/BIFF 파일도 수동으로 생성 할 수 있습니다. 그러나 거의 필요가 없습니다.)

.NET에서는 그렇게 할 수있는 구성 요소가있을 수 있다고 생각하지만, 클래식 ASP에서는 이미 HTML 테이블을 만들고 페이지의 MIME TIPE를 VND/MSEXCEL로 변경했습니다. GridView를 사용하고 Mime 유형을 변경하면 GridView가 HTML 테이블이기 때문에 작동해야한다고 생각합니다.

"이 숫자가 텍스트로 저장되는 것처럼 보이는"녹색 삼각형을 피하는 유일한 방탄 방법은 열린 XML 형식을 사용하는 것입니다. 피할 수없는 녹색 삼각형을 피하기 위해 사용하는 것이 좋습니다.

Excel 보고서에서 본 가장 좋은 방법은 XML 확장자와 함께 XML의 데이터를 작성하고 올바른 콘텐츠 유형으로 클라이언트로 스트리밍하는 것입니다. (응용 프로그램/XLS)

이는 기본 형식이 필요한 모든 보고서에 대해 작동하며 텍스트 비교 도구를 사용하여 기존 스프레드 시트와 비교할 수 있습니다.

이것이 권한을 설정하고 권한을 설정할 수있는 인트라넷을위한 것이라고 가정하면, 통합 문서 클라이언트 측을 jscript/vbscript drive excel. 이것은 서버에서 Excel을 자동화하려는 번거 로움없이 기본 Excel 형식을 제공합니다.

나는 상당히 틈새 시나리오를 제외 하고이 접근법을 더 이상 추천할지 모르겠지만, 클래식 ASP Heydays에서는 상당히 일반적이었습니다.

물론 항상 타사 구성 요소를 찾을 수 있습니다. 개인적으로 나는 spire.xls에 대한 좋은 경험을했습니다. http://www.e-iceblue.com/xls/xlsintro.htm

구성 요소는 응용 프로그램 내에서 사용하기 쉽습니다.

        Workbook workbook = new Workbook();

        //Load workbook from disk.
        workbook.LoadFromFile(@"Data\EditSheetSample.xls");
        //Initailize worksheet
        Worksheet sheet = workbook.Worksheets[0];

        //Writes string
        sheet.Range["B1"].Text = "Hello,World!";
        //Writes number
        sheet.Range["B2"].NumberValue = 1234.5678;
        //Writes date
        sheet.Range["B3"].DateTimeValue = System.DateTime.Now;
        //Writes formula
        sheet.Range["B4"].Formula = "=1111*11111";

        workbook.SaveToFile("Sample.xls");

위에서 제안한 솔루션 중 하나를 사용하여 제가 실행 한 문제 중 하나는 이 답변 컨텐츠를 첨부 파일로 푸시하는 경우 (MS 브라우저가 아닌 브라우저에서 가장 깨끗한 솔루션 인 것으로 밝혀지면) Excel 2000-2003에서 열면 그 유형은 "Excel 웹 페이지"입니다. 네이티브 엑셀 문서.

그런 다음 Excel 내에서 "유형으로 저장"을 사용하여 Excel 문서로 변환하는 방법을 사용자에게 설명해야합니다. 사용자 가이 문서를 편집 한 다음 사이트에 다시 업로드 해야하는 경우 고통입니다.

내 추천은 CSV를 사용하는 것입니다. 간단하고 사용자가 Excel 내에서 열면 Excel이 최소한 기본 형식으로 저장하도록 촉구합니다.

데이터를 기반으로 CSV 파일을 만들 것입니다. 왜냐하면 가장 깨끗한 것으로보고 Excel은 그것에 대해 잘 지원한다고 생각합니다. 그러나보다 유연한 형식이 필요한 경우 실제 Excel 파일을 생성하기위한 타사 도구가 있다고 확신합니다.

다음은 DataTable을 CSV로 스트림하는 솔루션입니다. 빠르고 깨끗하며 쉽고 입력에서 쉼표를 처리합니다.

public static void ExportToExcel(DataTable data, HttpResponse response, string fileName)
{
    response.Charset = "utf-8";
    response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
    response.Cache.SetCacheability(HttpCacheability.NoCache);
    response.ContentType = "text/csv";
    response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);

    for (int i = 0; i < data.Columns.Count; i++)
    {
       response.Write(data.Columns[i].ColumnName);
       response.Write(i == data.Columns.Count - 1 ? "\n" : ",");
    }        
    foreach (DataRow row in data.Rows)
    {
        for (int i = 0; i < data.Columns.Count; i++)
        {
            response.Write(String.Format("\"{0}\"", row[i].ToString()));
            response.Write(i == data.Columns.Count - 1 ? "\n" : ",");
        }
    }

    response.End();
}

방금 웹 양식 C#에서 내보내기 위해 기능을 만들었습니다.

    public void ExportFileFromSPData(string filename, DataTable dt)
    {
        HttpResponse response = HttpContext.Current.Response;

        //clean up the response.object
        response.Clear();
        response.Buffer = true;
        response.Charset = "";

        // set the response mime type for html so you can see what are you printing 
        //response.ContentType = "text/html";
        //response.AddHeader("Content-Disposition", "attachment;filename=test.html");

        // set the response mime type for excel
        response.ContentType = "application/vnd.ms-excel";
        response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
        response.ContentEncoding = System.Text.Encoding.UTF8;
        response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());

        //style to format numbers to string
        string style = @"<style> .text { mso-number-format:\@; } </style>";
        response.Write(style);

        // create a string writer
        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                // instantiate a datagrid
                GridView dg = new GridView();
                dg.DataSource = dt;
                dg.DataBind();

                foreach (GridViewRow datarow in dg.Rows)
                {
                    //format specific cell to be text 
                    //to avoid 1.232323+E29 to get 1232312312312312124124
                    datarow.Cells[0].Attributes.Add("class", "text");
                }

                dg.RenderControl(htw);
                response.Write(sw.ToString());
                response.End();
            }
        }
     }

CSV 파일 대신 Excel을 사용해야하는 경우 Excel 인스턴스에서 OLE Automation을 사용하여 서버입니다. 이 작업을 수행하는 가장 쉬운 방법은 템플릿 파일을 갖고 프로그래밍 방식으로 데이터로 채우는 것입니다. 다른 파일에 저장합니다.

팁 :

  • 대화식으로하지 마십시오. 사용자가 프로세스를 시작한 다음 파일 링크와 함께 페이지를 게시하도록하십시오. 스프레드 시트가 생성되는 동안 잠재적 성능 문제가 완화됩니다.
  • 앞에서 설명한대로 템플릿을 사용하십시오. 쉽게 수정할 수 있습니다.
  • Excel이 대화 상자를 팝업하지 않도록 설정되어 있는지 확인하십시오. 웹 서버에서는 전체 Excel 인스턴스가 걸립니다.
  • Excel 인스턴스를 별도의 서버, 바람직하게는 방화벽 뒤에 유지하므로 잠재적 인 보안 구멍으로 노출되지 않습니다.
  • 자원 사용을 주시하십시오. OLE 자동화 인터페이스를 통해 SpreadHseet를 생성하는 것은 상당히 헤비급 프로세스입니다. 이것을 높은 데이터 볼륨으로 확장 해야하는 경우 아키텍처에서 다소 영리해야 할 수도 있습니다.

파일의 형식이 약간 기본적이라는 것을 신경 쓰지 않으면 'Mime-Types를 사용하여 HTML 테이블을 여는 것'접근 방식 중 일부는 작동합니다. 이러한 접근 방식은 또한 CPU 무거운 작업을 고객에게 제공합니다. 스프레드 시트의 형식을 세밀하게 조정하려면 위에서 설명한대로 파일을 생성하려면 Excel 자체를 사용해야 할 것입니다.

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