利用OpenXml实现导出Excel

js入口

$(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<string> propnames = new List<string>();
            List<string> dispnames = new List<string>();
            List<int> _fieldtypes = new List<int>();
            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>();
                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<Cell> cells = new List<Cell>();
            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<Cell> cells = new List<Cell>();
            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<CellValues>(dataType)
            };
        }


    }
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页