码迷,mamicode.com
首页 > Web开发 > 详细

MVC中FileResult 返回类型返回Excel

时间:2018-05-22 10:37:35      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:导出   i++   html4   param   div   exe   exception   类型   tst   

公司中以前写的导出有问题。原来使用的XML格式字符串拼接然后转化成流输出

action

        public FileResult ExportJobFair()
        {
            try
            {

                string name = "t";
                int lblx = int.Parse(Request.QueryString["LBLX"]);
                string filename = name + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
                byte[] excelbyte = new RecruitmentMeeting().ExportJobFair(Request.QueryString["LBLX"]);
                return File(excelbyte, @"application/ms-excel", filename);

            }
            catch (Exception)
            {
                return null;
            }
        }

XML字符串拼接

    public byte[] ExportJobFair(string lblx)
        {
            try
            {
                //生成execl
                string name = "招聘会列表";
                string muban1 = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><?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\" xmlns:dt=\"uuid:C2F41010-65B3-11d1-A29F-00AA00C14882\"><DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\"><Author>User</Author><LastAuthor>User</LastAuthor><Created>2017-01-12T03:15:00Z</Created><LastSaved>2017-01-12T03:46:32Z</LastSaved></DocumentProperties><CustomDocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\"><KSOProductBuildVer dt:dt=\"string\">2052-10.1.0.6135</KSOProductBuildVer></CustomDocumentProperties><ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\"><WindowWidth>28695</WindowWidth><WindowHeight>13050</WindowHeight><ProtectStructure>False</ProtectStructure><ProtectWindows>False</ProtectWindows></ExcelWorkbook><Styles><Style ss:ID=\"s29\" ss:Name=\"链接单元格\"><Borders><Border ss:Position=\"Bottom\" ss:LineStyle=\"Double\" ss:Weight=\"3\" ss:Color=\"#FF8001\"/></Borders><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#FA7D00\"/></Style><Style ss:ID=\"s19\" ss:Name=\"标题 1\"><Borders><Border ss:Position=\"Bottom\" ss:LineStyle=\"Continuous\" ss:Weight=\"2\" ss:Color=\"#4472C4\"/></Borders><Font ss:FontName=\"等线\" x:CharSet=\"134\" ss:Size=\"15\" ss:Color=\"#44546A\" ss:Bold=\"1\"/></Style><Style ss:ID=\"s13\" ss:Name=\"注释\"><Borders><Border ss:Position=\"Bottom\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#B2B2B2\"/><Border ss:Position=\"Left\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#B2B2B2\"/><Border ss:Position=\"Right\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#B2B2B2\"/><Border ss:Position=\"Top\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#B2B2B2\"/></Borders><Interior ss:Color=\"#FFFFCC\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s8\" ss:Name=\"千位分隔\"></Style><Style ss:ID=\"s22\" ss:Name=\"标题 3\"><Borders><Border ss:Position=\"Bottom\" ss:LineStyle=\"Continuous\" ss:Weight=\"2\" ss:Color=\"#A2B8E1\"/></Borders><Font ss:FontName=\"等线\" x:CharSet=\"134\" ss:Size=\"11\" ss:Color=\"#44546A\" ss:Bold=\"1\"/></Style><Style ss:ID=\"s17\" ss:Name=\"标题\"><Font ss:FontName=\"等线\" x:CharSet=\"134\" ss:Size=\"18\" ss:Color=\"#44546A\" ss:Bold=\"1\"/></Style><Style ss:ID=\"s10\" ss:Name=\"超链接\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#0000FF\" ss:Underline=\"Single\"/></Style><Style ss:ID=\"s7\" ss:Name=\"差\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#9C0006\"/><Interior ss:Color=\"#FFC7CE\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s15\" ss:Name=\"标题 4\"><Font ss:FontName=\"等线\" x:CharSet=\"134\" ss:Size=\"11\" ss:Color=\"#44546A\" ss:Bold=\"1\"/></Style><Style ss:ID=\"s5\" ss:Name=\"千位分隔[0]\"></Style><Style ss:ID=\"s24\" ss:Name=\"输出\"><Borders><Border ss:Position=\"Bottom\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#3F3F3F\"/><Border ss:Position=\"Left\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#3F3F3F\"/><Border ss:Position=\"Right\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#3F3F3F\"/><Border ss:Position=\"Top\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#3F3F3F\"/></Borders><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#3F3F3F\" ss:Bold=\"1\"/><Interior ss:Color=\"#F2F2F2\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s3\" ss:Name=\"输入\"><Borders><Border ss:Position=\"Bottom\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#7F7F7F\"/><Border ss:Position=\"Left\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#7F7F7F\"/><Border ss:Position=\"Right\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#7F7F7F\"/><Border ss:Position=\"Top\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#7F7F7F\"/></Borders><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#3F3F76\"/><Interior ss:Color=\"#FFCC99\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s4\" ss:Name=\"货币\"></Style><Style ss:ID=\"s31\" ss:Name=\"好\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#006100\"/><Interior ss:Color=\"#C6EFCE\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s20\" ss:Name=\"标题 2\"><Borders><Border ss:Position=\"Bottom\" ss:LineStyle=\"Continuous\" ss:Weight=\"2\" ss:Color=\"#4472C4\"/></Borders><Font ss:FontName=\"等线\" x:CharSet=\"134\" ss:Size=\"13\" ss:Color=\"#44546A\" ss:Bold=\"1\"/></Style><Style ss:ID=\"s16\" ss:Name=\"警告文本\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#FF0000\"/></Style><Style ss:ID=\"s1\" ss:Name=\"货币[0]\"></Style><Style ss:ID=\"s30\" ss:Name=\"汇总\"><Borders><Border ss:Position=\"Bottom\" ss:LineStyle=\"Double\" ss:Weight=\"3\" ss:Color=\"#4472C4\"/><Border ss:Position=\"Top\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#4472C4\"/></Borders><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\" ss:Bold=\"1\"/></Style><Style ss:ID=\"s11\" ss:Name=\"百分比\"><NumberFormat ss:Format=\"0%\"/></Style><Style ss:ID=\"Default\" ss:Name=\"Normal\"><Alignment/><Borders/><Font ss:FontName=\"等线\" x:CharSet=\"134\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior/><NumberFormat/><Protection/></Style><Style ss:ID=\"s40\" ss:Name=\"强调文字颜色 4\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#CCE8CF\"/><Interior ss:Color=\"#FFC000\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s37\" ss:Name=\"20% - 强调文字颜色 2\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior ss:Color=\"#FCE4D6\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s32\" ss:Name=\"适中\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#9C6500\"/><Interior ss:Color=\"#FFEB9C\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s6\" ss:Name=\"40% - 强调文字颜色 3\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior ss:Color=\"#DBDBDB\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s36\" ss:Name=\"40% - 强调文字颜色 1\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior ss:Color=\"#B4C6E7\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s2\" ss:Name=\"20% - 强调文字颜色 3\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior ss:Color=\"#EDEDED\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s47\" ss:Name=\"40% - 强调文字颜色 6\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior ss:Color=\"#C6E0B4\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s9\" ss:Name=\"60% - 强调文字颜色 3\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#CCE8CF\"/><Interior ss:Color=\"#C9C9C9\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s35\" ss:Name=\"20% - 强调文字颜色 1\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior ss:Color=\"#D9E1F2\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s18\" ss:Name=\"解释性文本\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#7F7F7F\" ss:Italic=\"1\"/></Style><Style ss:ID=\"s12\" ss:Name=\"已访问的超链接\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#800080\" ss:Underline=\"Single\"/></Style><Style ss:ID=\"s33\" ss:Name=\"20% - 强调文字颜色 5\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior ss:Color=\"#DDEBF7\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s28\" ss:Name=\"强调文字颜色 2\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#CCE8CF\"/><Interior ss:Color=\"#ED7D31\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s14\" ss:Name=\"60% - 强调文字颜色 2\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#CCE8CF\"/><Interior ss:Color=\"#F4B084\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s38\" ss:Name=\"40% - 强调文字颜色 2\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior ss:Color=\"#F8CBAD\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s27\" ss:Name=\"20% - 强调文字颜色 6\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior ss:Color=\"#E2EFDA\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s21\" ss:Name=\"60% - 强调文字颜色 1\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#CCE8CF\"/><Interior ss:Color=\"#8EA9DB\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s42\" ss:Name=\"40% - 强调文字颜色 4\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior ss:Color=\"#FFE699\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s41\" ss:Name=\"20% - 强调文字颜色 4\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior ss:Color=\"#FFF2CC\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s25\" ss:Name=\"计算\"><Borders><Border ss:Position=\"Bottom\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#7F7F7F\"/><Border ss:Position=\"Left\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#7F7F7F\"/><Border ss:Position=\"Right\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#7F7F7F\"/><Border ss:Position=\"Top\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\" ss:Color=\"#7F7F7F\"/></Borders><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#FA7D00\" ss:Bold=\"1\"/><Interior ss:Color=\"#F2F2F2\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s23\" ss:Name=\"60% - 强调文字颜色 4\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#CCE8CF\"/><Interior ss:Color=\"#FFD966\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s48\" ss:Name=\"60% - 强调文字颜色 6\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#CCE8CF\"/><Interior ss:Color=\"#A9D08E\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s46\" ss:Name=\"强调文字颜色 6\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#CCE8CF\"/><Interior ss:Color=\"#70AD47\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s39\" ss:Name=\"强调文字颜色 3\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#CCE8CF\"/><Interior ss:Color=\"#A5A5A5\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s26\" ss:Name=\"检查单元格\"><Borders><Border ss:Position=\"Bottom\" ss:LineStyle=\"Double\" ss:Weight=\"3\" ss:Color=\"#3F3F3F\"/><Border ss:Position=\"Left\" ss:LineStyle=\"Double\" ss:Weight=\"3\" ss:Color=\"#3F3F3F\"/><Border ss:Position=\"Right\" ss:LineStyle=\"Double\" ss:Weight=\"3\" ss:Color=\"#3F3F3F\"/><Border ss:Position=\"Top\" ss:LineStyle=\"Double\" ss:Weight=\"3\" ss:Color=\"#3F3F3F\"/></Borders><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#FFFFFF\" ss:Bold=\"1\"/><Interior ss:Color=\"#A5A5A5\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s34\" ss:Name=\"强调文字颜色 1\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#CCE8CF\"/><Interior ss:Color=\"#4472C4\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s45\" ss:Name=\"60% - 强调文字颜色 5\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#CCE8CF\"/><Interior ss:Color=\"#9BC2E6\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s44\" ss:Name=\"40% - 强调文字颜色 5\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#000000\"/><Interior ss:Color=\"#BDD7EE\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s43\" ss:Name=\"强调文字颜色 5\"><Font ss:FontName=\"等线\" x:CharSet=\"0\" ss:Size=\"11\" ss:Color=\"#CCE8CF\"/><Interior ss:Color=\"#5B9BD5\" ss:Pattern=\"Solid\"/></Style><Style ss:ID=\"s49\"/><Style ss:ID=\"s50\"><Alignment ss:Horizontal=\"Center\"/></Style><Style ss:ID=\"s51\"><Alignment/></Style><Style ss:ID=\"s52\"><Alignment ss:Horizontal=\"Center\"/></Style></Styles><Worksheet ss:Name=\"Sheet2\"><Table ss:ExpandedColumnCount=\"3\" ss:ExpandedRowCount=\"4\" x:FullColumns=\"1\" x:FullRows=\"1\" ss:DefaultColumnWidth=\"54\" ss:DefaultRowHeight=\"14.25\">";
                string muban2 = "<Row><Cell ss:StyleID=\"s52\" ss:MergeAcross=\"3\"><Data ss:Type=\"String\">" + name + "</Data></Cell></Row><Row><Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">招聘会名称</Data></Cell><Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">申请截止时间</Data></Cell><Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">开始时间</Data></Cell><Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">结束时间</Data></Cell><Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">地点</Data></Cell></Row>";
                string muban3 = "</Table><WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\"><PageSetup><Header x:Margin=\"0.3\"/><Footer x:Margin=\"0.3\"/><PageMargins x:Left=\"0.699305555555556\" x:Right=\"0.699305555555556\" x:Top=\"0.75\" x:Bottom=\"0.75\"/></PageSetup><Selected/><TopRowVisible>0</TopRowVisible><LeftColumnVisible>0</LeftColumnVisible><PageBreakZoom>100</PageBreakZoom><Panes><Pane><Number>3</Number><ActiveRow>0</ActiveRow><ActiveCol>0</ActiveCol><RangeSelection>R1C1:R2C3</RangeSelection></Pane></Panes><ProtectObjects>False</ProtectObjects><ProtectScenarios>False</ProtectScenarios></WorksheetOptions></Worksheet><Worksheet ss:Name=\"Sheet1\"><Table ss:ExpandedColumnCount=\"1\" ss:ExpandedRowCount=\"1\" x:FullColumns=\"1\" x:FullRows=\"1\" ss:DefaultColumnWidth=\"54\" ss:DefaultRowHeight=\"14.25\"/><WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\"><PageSetup><Header x:Margin=\"0.3\"/><Footer x:Margin=\"0.3\"/><PageMargins x:Left=\"0.699305555555556\" x:Right=\"0.699305555555556\" x:Top=\"0.75\" x:Bottom=\"0.75\"/></PageSetup><TopRowVisible>0</TopRowVisible><LeftColumnVisible>0</LeftColumnVisible><PageBreakZoom>100</PageBreakZoom><ProtectObjects>False</ProtectObjects><ProtectScenarios>False</ProtectScenarios></WorksheetOptions></Worksheet></Workbook>";
                if (int.Parse(lblx) == 4)
                {
                    muban2 = "<Row><Cell ss:StyleID=\"s52\" ss:MergeAcross=\"4\"><Data ss:Type=\"String\">" + name + "</Data></Cell></Row><Row><Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">招聘会名称</Data></Cell><Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">空余展位/总展位数</Data></Cell><Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">申请截止时间</Data></Cell><Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">开始时间</Data></Cell><Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">结束时间</Data></Cell></Row>";
                }
          //查询类型 ZphListParam cs
= new ZphListParam(); cs.MYHS = 0; cs.YM = 0; cs.LBLX = lblx; cs.PXFS = "ASC"; cs.PXZD = "DHMC"; ProcessResult pro = new RecruitmentMeeting().Query(cs); 查询结果列表对象 ZPH = JsonHelper.JsonDeserialize<查询结果列表对象>(pro.ResultJson); IList<ZhaopinhuiJson4Query> rows = ZPH.Result.rows; if (ZPH.IsOK == true && rows.Count > 0) { //序号 for (int i = 0; i < rows.Count; i++) { muban2 += "<Row><Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">" + Common.DecodeString(rows[i].DHMC) + "</Data></Cell>"; if (int.Parse(lblx) == 4) { muban2 += "<Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">" + rows[i].KYZW + "/" + rows[i].ZZWS + "</Data></Cell>"; //muban2 += "<Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">" + rows[i].SQJSSJ + "</Data></Cell>"; muban2 += "<Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">" + rows[i].KSSJ + "</Data></Cell>"; muban2 += "<Cell ss:StyleID=\"s51\"><Data ss:Type=\"Number\">" + rows[i].JSSJ + "</Data></Cell></Row>"; } else { //muban2 += "<Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">" + rows[i].SQJSSJ + "</Data></Cell>"; muban2 += "<Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">" + rows[i].KSSJ + "</Data></Cell>"; muban2 += "<Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">" + rows[i].JSSJ + "</Data></Cell>"; muban2 += "<Cell ss:StyleID=\"s51\"><Data ss:Type=\"String\">" + Common.DecodeString(rows[i].DZ) + "</Data></Cell></Row>"; } } } string xmldata = muban1 + muban2 + muban3; byte[] xmlbytes = Encoding.Default.GetBytes(xmldata); return xmlbytes; } catch (Exception) { return null; } }

数据库语句执行完返回的数据类型

    public class ProcessResult
    {
        /// <summary>
        /// 调用是否成功
        /// </summary>
        public Boolean IsOK { get; set; }

        /// <summary>
        /// 调用是否成功的文字描述
        /// </summary>
        public String Message { get; set; }

        /// <summary>
        /// 调用返回对象
        /// </summary>
        public Object ResultObj { get; set; }

        /// <summary>
        /// 调用返回值的JSON表示
        /// </summary>
        public String ResultJson { get; set; }

        /// <summary>
        /// 获取与设置表格字段名
        /// </summary>
        public string[] Head { get; set; }

        /// <summary>
        /// 表格标题
        /// </summary>
        public string[] HeadText { get; set; }

        /// <summary>
        /// 标题列宽
        /// </summary>
        public int[] HeadWidth { get; set; }

        /// <summary>
        /// 调用受影响的数据行数
        /// 对于查询语句,返回符合查询条件的总行数
        /// 对于修改语句,返回被更新的数据的总行数
        /// </summary>
        public int RowCount { get; set; }

        public int Total { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ok">调用是否成功</param>
        /// <param name="msg">调用是否成功的文字描述</param>
        /// <param name="obj">调用返回对象</param>
        /// <param name="json">调用返回值的JSON表示</param>
        /// <param name="count">调用受影响的数据行数</param>
        public ProcessResult(bool ok, string msg, object obj, string json, int count)
        {
            IsOK = ok;
            Message = msg;
            ResultObj = obj;
            ResultJson = json;
            RowCount = count;
        }

        public ProcessResult()
        {
        }
    }

然后发现生成的XML返回EXCEL 程序不认,office excel和WPS均无法打开。提示文件损坏,只能选择重写

因为涉及的地方比较多,时间也比较充裕于是写了一个简单是帮助类

(提示:项目需要引用 Microsoft.Office.Interop)

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;namespace Utility
{
    public class ExcelHelper
    {
        /// <summary>
        /// DataTable导出excel
        /// 返回保存的地址
        /// </summary>
        /// <param name="datas">数据源</param>
        /// <param name="p">保存路径</param>
        /// <returns></returns>
        public static string DataTableToExcel(DataTable datas, string p)
        {
            Microsoft.Office.Interop.Excel.Application app =
                new Microsoft.Office.Interop.Excel.Application();
            try
            {
                app.Visible = false;
                Microsoft.Office.Interop.Excel.Workbook wBook = app.Workbooks.Add(true);
                Microsoft.Office.Interop.Excel.Worksheet wSheet = wBook.Sheets[1];
                wSheet.Name = "shhel";
                if (datas.Rows.Count > 0)
                {
                    int row = datas.Rows.Count;
                    int col = datas.Columns.Count;
                    for (int i = 0; i < row; i++)
                    {
                        for (int j = 0; j < col; j++)
                        {
                            string str = "-";
                            if (datas.Rows[i][j].Equals(float.NaN) == false)
                            {
                                str = datas.Rows[i][j].ToString();

                            }
                            wSheet.Cells[i + 2, j + 1] = str;
                        }
                    }
                }

                int size = datas.Columns.Count;
                for (int i = 0; i < size; i++)
                {
                    wSheet.Cells[1, 1 + i] = datas.Columns[i].ColumnName;
                }
                //列自适应
                wSheet.Columns.EntireColumn.AutoFit();
                //设置禁止弹出保存和覆盖的询问提示框     
                app.DisplayAlerts = false;
                app.AlertBeforeOverwriting = false;
                //保存工作簿   
                //wBook.Save();  
                wSheet.SaveAs(p);
                wBook.Close();
                //保存excel文件     
                //app.Save(filePath);  
                //app.SaveWorkspace(filePath);  
                app.Quit();
                GC.Collect();
            }
            catch (Exception)
            {

                //强制结束excel进程  
                IntPtr t = new IntPtr(app.Hwnd);


            }
            return p;
        }


        /// <summary>
        /// 泛型集合转DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(IList<T> items)
        {
            if (items==null)
            {
            return null;
            }
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in props)
            {
                tb.Columns.Add(prop.Name);
            }

            foreach (T item in items)
            {
                var values = new object[props.Length];

                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }

            return tb;
        }
    }
}

写好后的Action调用

        public FileResult ExportJobFairExcel()
        {
            try
            {

                string name = "招聘会列表";
                int lblx = int.Parse(Request.QueryString["LBLX"]);

                string filename = name + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                DataTable dt = new RecruitmentMeeting().ExportJobFairDatatable(Request.QueryString["LBLX"]);
                string strdate = DateTime.Now.ToString("yyyyMMddhhmmss");
                string str = Server.HtmlEncode(Request.PhysicalApplicationPath).ToString() + "File\\Excel\\" + filename;
                string file = Utility.ExcelHelper.DataTableToExcel(dt, str);
                return File(file, "application/vnd.ms-excel", filename);
            }
            catch (Exception)
            {
                return null;
            }
        }

其中时间格式算个坑吧,第一次导出的时候时间无转换,导出的excel打开时间的列都是#####,

        public DataTable ExportJobFairDatatable(string lblx)
        {
            try
            {
                //生成execl
                string name = "招聘会列表";

                ZphListParam cs = new ZphListParam();
                cs.MYHS = 0;
                cs.YM = 0;
                cs.LBLX = lblx;
                cs.PXFS = "ASC";
                cs.PXZD = "DHMC";
                ProcessResult pro = new RecruitmentMeeting().Query(cs);
                招聘会查询结果列表对象 ZPH = JsonHelper.JsonDeserialize<招聘会查询结果列表对象>(pro.ResultJson);
                IList<JobFair> rows = new List<JobFair>();
                foreach (ZhaopinhuiJson4Query item in ZPH.Result.rows)
                {
                    JobFair jf = new JobFair();
            //Common.DecodeString方法是用于加密后的数据解码的 jf.招聘会名称
= Common.DecodeString(item.DHMC); jf.开始时间 = Convert.ToDateTime(item.KSSJ).Year + "" + Convert.ToDateTime(item.KSSJ).Month + "" + Convert.ToDateTime(item.KSSJ).Day + ""; jf.结束时间 = Convert.ToDateTime(item.JSSJ).Year + "" + Convert.ToDateTime(item.JSSJ).Month + "" + Convert.ToDateTime(item.JSSJ).Day + ""; jf.地点 = Common.DecodeString(item.DZ); rows.Add(jf); } DataTable dt = ExcelHelper.ToDataTable<JobFair>(rows); if (int.Parse(lblx) == 4) { dt.Columns.Add("空余展位/总展位"); for (int i = 0; i < ZPH.Result.rows.Count; i++) { dt.Rows[i]["空余展位/总展位"] = ZPH.Result.rows[i].KYZW + "/" + ZPH.Result.rows[i].ZZWS; } } return dt; } catch (Exception) { return null; } }
    /// <summary>
    /// 公共招聘会导出模型
    /// </summary>
    public class JobFair
    {
        /// <summary>
        /// 招聘会名称
        /// 使用前需解码
        /// </summary>
        public string 招聘会名称 { get; set; }

        /// <summary>
        /// 开始时间
        /// yyyy-MM-dd HH:mm:ss
        /// </summary>
        public string 开始时间 { get; set; }

        /// <summary>
        /// 结束时间
        /// yyyy-MM-dd HH:mm:ss
        /// </summary>
        public string 结束时间 { get; set; }

        /// <summary>
        /// 地址
        /// 使用前需解码
        /// </summary>
        public string 地点 { get; set; }

    }

实际上如果直接用datatable会更快一点,但是因为其他地方也用到了所以为了节约时间直接进行了2次转换。

如果有需要的可以直接把导出的excel文件的方法重载一下。

MVC中FileResult 返回类型返回Excel

标签:导出   i++   html4   param   div   exe   exception   类型   tst   

原文地址:https://www.cnblogs.com/SakugamiTomoyo/p/9070521.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!