OpenXml을 사용하여 Excel 내보내기

8590 단어
입구
$(function() {
    $(window.parent.document)
        .find("#divToolbar").find("td")
        .each(function() {
            var id = $(this).attr("id");
            if (id == "tdCreateNew" ||
                id == "tdCreateByGrid" ||
                id == "tdShowAllWork" ||
                id == "tdDataImport" ||
                id == "tdHelp" ||
                id == "tdCustomDef" ||
                id == "tdSearchCentra" ||
                id == "tdSearchAll"
            ) {
                $(this).prev().hide();
                $(this).hide();
            }
        });

    $("#imgExport").removeAttr("onclick").click(function () {
        var urlData = getAppPath() + "/Yshd/Other/ExportToExcelByTid.aspx" +
                   "?tid=" + tid;
        $.get(_akUrl(urlData), function (data) {
            var path = data;
            var url = getAppPath() + "/Components/UpAndDown/Download.aspx" +
                       "?path=" + escape(path);
            loadHideFrame(url, false, window.parent.parent);
        });
    });

});

ExportToExcelByTid 코드 내보내기.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using CpmBigDataImportService;
using System.Data;
using Appkit.Common;
using Appkit.Data;
using Appkit.Web.Management;

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Xml;
public partial class Yshd_Other_ExportToExcelByTid : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string tid = AkCommon.GetQueryString("tid");

        SearchCache cache = new SearchCache(tid);
        string cond = cache.SQLExpression;
        cond = (cond.Length == 0) ? cond : string.Format(" Where {0}", cond);
        SqlConnectConfig sqc = new SqlConnectConfig().ConfigByDbString(GetConnectionString(AkContext.AppId, AkContext.PrjId));


        MyType myType = new MyType(AkContext.AppId, cache.TypeName, sqc);

        string fileName = Appkit.IO.AkDirService.UserRuntimeTempDir + "\\" + cache.TypeName + ".xlsx";
        new Report().CreateExcelDoc(fileName, myType);


        Response.Write(fileName);

    }


    private string GetConnectionString(string appid, string prjid)
    {
        string result = "";
        XmlDocument doc = new XmlDocument();
        string dbConfigFileName = string.Format(@"d:\appkit\platform\lib\engine.xml");
        doc.Load(dbConfigFileName);

        string path = string.Format("engine/all_prj_list/prj_list[@app_id='{0}']/prj[@id='{1}']/db_list/db[@id='MAIN']/connstr"
                                    , UpperFisrtLetter(appid)
                                        , UpperFisrtLetter(prjid));
        XmlNode node = doc.SelectSingleNode(path);
        if (null != node)
        {
            result = node.FirstChild.Value;
        }
        return result;
    }

    private string UpperFisrtLetter(string str)
    {
        return str.Substring(0, 1).ToUpper() + str.Substring(1, str.Length - 1).ToLower();
    }

    private class MyType
    {
        private SqlConnectConfig sqc;

        public SqlConnectConfig Sqc
        {
            get { return sqc; }
        }
        private int[] fieldtypes;

        public int[] Fieldtypes
        {
            get { return fieldtypes; }
        }
        private string[] title;

        public string[] Title
        {
            get { return title; }
        }
        private string sql;

        public string Sql
        {
            get { return sql; }
        }

        public MyType() { }
        public MyType(string appid, string ele, SqlConnectConfig sqc)
        {
            this.sqc = sqc;

            AccessHelper acc = new AccessHelper(appid);
            string FieldsSql = string.Format("select prop_name,prop_dispname,prop_field_type from md_sys_property where ele_id in ( select ele_id from md_sys_element where ele_name='{0}')", ele);

            List propnames = new List();
            List dispnames = new List();
            List _fieldtypes = new List();
            DataTable dt = acc.ExecuteDataSet(acc.ConnectionString, FieldsSql).Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                propnames.Add(dt.Rows[i][0].ToString());
                dispnames.Add(dt.Rows[i][1].ToString());
                if (DBNull.Value == dt.Rows[i][2]
                    || dt.Rows[i][2].ToString().Length == 0)
                    _fieldtypes.Add(0);
                else
                    _fieldtypes.Add(int.Parse(dt.Rows[i][2].ToString()));
            }
            title = dispnames.ToArray();
            sql = string.Format("select {0} from {1}"
                , string.Join(",", propnames.ToArray())
                , ele);
            fieldtypes = _fieldtypes.ToArray();



        }


    }


    private class Report
    {
        public void CreateExcelDoc(string filename, MyType myType)
        {
            using (SpreadsheetDocument doc = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
            {
                WorkbookPart workbookPart = doc.AddWorkbookPart();
                workbookPart.Workbook = new Workbook();

                WorksheetPart worksheetPart = workbookPart.AddNewPart();
                worksheetPart.Worksheet = new Worksheet();

                Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());

                Sheet sheet = new Sheet()
                {
                    Id = workbookPart.GetIdOfPart(worksheetPart),
                    SheetId = 1,
                    Name = "Sheet1"
                };

                sheets.Append(sheet);

                workbookPart.Workbook.Save();

                SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());

                Row row = new Row();
                row.Append(GetTitle(myType));
                sheetData.AppendChild(row);

                DataTable dt = MyCommon.GetDt(myType.Sql, myType.Sqc.ConnectString);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    sheetData.AppendChild(GetRow(dt.Rows[i], myType.Fieldtypes));
                }


                worksheetPart.Worksheet.Save();
            }
        }

        private Row GetRow(DataRow dr, int[] types)
        {
            Row row = new Row();
            List cells = new List();
            object[] arr = dr.ItemArray;
            for (int i = 0; i < arr.Length; i++)
            {
                cells.Add(ConstructCell(arr[i].ToString()
                    , GetCellValues(types[i])));
            }
            row.Append(cells.ToArray());
            return row;
        }

        private Cell[] GetTitle(MyType myType)
        {
            List cells = new List();
            for (int i = 0; i < myType.Title.Length; i++)
            {
                cells.Add(ConstructCell(myType.Title[i]
                    , CellValues.String));
                //GetCellValues(myType.Fieldtypes[i])
            }
            return cells.ToArray();
        }

        private CellValues GetCellValues(int t)
        {
            CellValues result;
            switch (t)
            {
                case 0:
                    result = CellValues.Number;
                    break;
                case 1:
                    result = CellValues.String;
                    break;
                case 3:
                case 7:
                    result = CellValues.String; // 、 
                    break;


                default:
                    //throw new Exception("GetCellValues");
                    result = CellValues.String;
                    break;
            }
            return result;
        }

        private Cell ConstructCell(string value, CellValues dataType)
        {
            return new Cell()
            {
                CellValue = new CellValue(value),
                DataType = new EnumValue(dataType)
            };
        }


    }
}

좋은 웹페이지 즐겨찾기