DataSet 데이터를 Excel 문서로 내보내기(DataTable당 Sheet)

17224 단어 Datatable
웹 프로젝트에서 조회된 데이터 집합을 Excel 문서로 내보내는 기능을 실현해야 하는 경우가 많고, 프로젝트에 Office 구성 요소와 관련된 DLL에 대한 인용을 추가하지 않으려는 경우가 많고, 심지어는 Office의 다른 버전의 영향을 받아 서로 다른 서버에 배치된 후 기능이 제한되거나 다른 프로젝트와 충돌하는 경우도 있다.일부 원숭이 영장동물의 번뇌와 근심을 해결할 수 있다.
/// <summary>

/// DataSet Excel ( Sheet)

/// </summary>

/// <param name="dataSet">DataSet</param>

/// <param name="fileName"> </param>

/// <returns> </returns>

public static bool DataSetToExcel(DataSet dataSet, string fileName)

{

    if (dataSet == null) return false;

    if (dataSet.Tables.Count < 1) return false;

    if (dataSet.Tables[0] == null) return false;

    if (string.IsNullOrWhiteSpace(fileName)) return false;

    try

    {

        ExecDataSetToExcel(dataSet, fileName);

        return true;

    }

    catch (Exception ex)

    {

        //DO LOG

        return false;

    }

}
//  DataSet  

private static void ExecDataSetToExcel(DataSet dataSet, string fileName)

{

    HttpResponse httpResponse = HttpContext.Current.Response;

    httpResponse.Clear();

    httpResponse.Charset = "utf-8";

    httpResponse.ContentType = "text/xml";

    httpResponse.ContentEncoding = System.Text.Encoding.UTF8;

    httpResponse.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8) + ".xls");



    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < dataSet.Tables.Count; i++)

    {

        System.Data.DataTable dt = dataSet.Tables[i];

        // Sheet

        string sheetName = string.IsNullOrWhiteSpace(dt.TableName) ? "Sheet" + (i + 1) : dt.TableName;

        sb.Append("<Worksheet ss:Name='" + sheetName + "'>");

        sb.Append("<Table x:FullColumns='1' x:FullRows='1' ss:DefaultColumnWidth='118'>");

        // 

        sb.Append("<Row ss:AutoFitHeight='1'>");

        for (int j = 0; j < dt.Columns.Count; j++) sb.Append("<Cell ss:StyleID='header'><Data ss:Type='String'>" + dt.Columns[j].ColumnName + "</Data></Cell>");

        sb.Append("</Row>");

        // 

        for (int k = 0; k < dt.Rows.Count; k++)

        {

            sb.Append("<Row>");

            for (int l = 0; l < dt.Columns.Count; l++)

            {

                //Type ct = dt.Columns[l].DataType;

                //sb.Append("<Cell ss:StyleID='body'><Data ss:Type='Number'>" + dt.Rows[k][l] + "</Data></Cell>"); // 

                sb.Append("<Cell ss:StyleID='body'><Data ss:Type='String'>" + dt.Rows[k][l] + "</Data></Cell>");

            }

            sb.Append("</Row>");

        }

        sb.Append("</Table>");

        sb.Append("</Worksheet>");

    }



    string excelXmlDoc = CreateExcelXmlDoc(sb.ToString());

    httpResponse.Write(excelXmlDoc);

    httpResponse.Flush();

    httpResponse.End();

}
// Excel XML 

private static string CreateExcelXmlDoc(string worksheetXml)

{

    StringBuilder sb = new StringBuilder();

    sb.Append("<?xml version='1.0'?><?mso-application progid='Excel.Sheet'?>");

    sb.Append("<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'>");

    // 

    sb.Append("<DocumentProperties xmlns='urn:schemas-microsoft-com:office:office'>"

        + "<Author>Unitech</Author><LastAuthor>Unitech</LastAuthor><Created></Created><LastSaved></LastSaved><Version>12.00</Version>"

        + "</DocumentProperties>");

    // 

    sb.Append("<Styles>");

    sb.Append("<Style ss:ID='header'>"

        + "<Font ss:FontName=' ' x:CharSet='134' ss:Size='10' ss:Color='#000000' ss:Bold='0'/>"

        + "<Alignment ss:Horizontal='Center' ss:Vertical='Center'/>"

        + "<Interior ss:Color='#d8d8d8' ss:Pattern='Solid'/>"

        + "<Borders>"

        + "<Border ss:Position='Bottom' ss:LineStyle='Continuous' ss:Weight='1' ss:Color='#bfbfbf'/>"

        + "<Border ss:Position='Left' ss:LineStyle='Continuous' ss:Weight='1' ss:Color='#bfbfbf'/>"

        + "<Border ss:Position='Right' ss:LineStyle='Continuous' ss:Weight='1' ss:Color='#bfbfbf'/>"

        + "<Border ss:Position='Top' ss:LineStyle='Continuous' ss:Weight='1' ss:Color='#bfbfbf'/>"

        + "</Borders></Style>");

    sb.Append("<Style ss:ID='body'>"

        + "<Font ss:FontName=' ' x:CharSet='134' ss:Size='10' ss:Color='#000000'/>"

        + "<Alignment ss:Vertical='Center'/>"

        + "<NumberFormat ss:Format='@'/>"

        + "<Borders>"

        + "<Border ss:Position='Bottom' ss:LineStyle='Continuous' ss:Weight='1' ss:Color='#bfbfbf'/>"

        + "<Border ss:Position='Left' ss:LineStyle='Continuous' ss:Weight='1' ss:Color='#bfbfbf'/>"

        + "<Border ss:Position='Right' ss:LineStyle='Continuous' ss:Weight='1' ss:Color='#bfbfbf'/>"

        + "<Border ss:Position='Top' ss:LineStyle='Continuous' ss:Weight='1' ss:Color='#bfbfbf'/>"

        + "</Borders></Style>");

    sb.Append("</Styles>");

    //Work Sheet

    sb.Append(worksheetXml);

    sb.Append("</Workbook>");

    return sb.ToString();

}

필요한 것은 가져가서 스스로 개선하고 최적화하세요.

좋은 웹페이지 즐겨찾기