C#中 实现导出excel文件

文章讲述了在页面视图上如何使用JavaScript实现一个导出操作日志的按钮,通过AJAX发送请求到服务器,调用Controller中的ExportSysOperateLogs方法并下载Excel文件。
摘要由CSDN通过智能技术生成

页面视图上——按钮

 $('#ExportSysOperateLogs').linkbutton({ iconCls: 'icon-excel' });
 $("#ExportSysOperateLogs").click(function () { ExportSysOperateLogs(); });

页面视图上——按钮事件

function ExportSysOperateLogs() {
        var Text = "操作日志信息";
        var checkId = $("#clientTable").datagrid('getRows');
        if (checkId.length > 0) {
            var url = "/Queycount/ExportSysOperateLogs?"
                + "Startbirthday=" + Startbirthday
                + "&Endbirthday=" + Endbirthday
                    + "&Text=" + Text;
            $("#frmExportToExcels").attr("action", url).submit();
        } else {

            $.messager.alert("提示", "请你查询数据!");
        }
    }

from事件

<form id="frmExportToExcels" action="" method="post"></form>

控制器中

public ActionResult ExportSysOperateLogs()
        {        
            AddTmLog("导出", "日志", "导出日志信息");
            string Startbirthday = Request["Startbirthday"];
            string Endbirthday = Request["Endbirthday"];
            var data = new WJ.Terminal.Bll.Jiuding.JiudingBll().GetSysOperateLogs(Startbirthday, Endbirthday);
            string Text = Request["Text"];
            List<ExportSysOperateLogs> ejmList = new List<ExportSysOperateLogs>();
            ExportSysOperateLogs ejm = null;
            foreach (var item in data)
            {
                ejm = new ExportSysOperateLogs()
                {
                    SOL_ID = item.SOL_ID,
                    OPERATE_TIME = item.OPERATE_TIME,
                    OPERATE_TYPE = item.OPERATE_TYPE,
                    PARAMA = item.PARAMA,
                    PARAMA_SOURCE = item.PARAMA_SOURCE,
                    RETURNS_RESULTS = item.RETURNS_RESULTS,
                    REMARK = item.REMARK
                };
                ejmList.Add(ejm);
            }
            if (ejmList.Count > 0)
            {
                string[] cellNames = { "系统日志ID", "操作时间", "操作类型", "参数", "源参数", "返回结果", "备注" };

                string fileName = "操作日志信息_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";

                return new DownloadFileExcelHeader(cellNames, fileName, ejmList, Text);

            }
            return RedirectToAction("/SysOperateLogs");

        }

导出有表头excel文件

public class DownloadFileExcelHeader : ActionResult
    {
        public string fileName { get; set; }
        HSSFWorkbook book = new HSSFWorkbook();

        /// <summary>
        /// 导出excel函数
        /// </summary>
        /// <param name="cellNames">每列标题</param>
        /// <param name="pFileName">excel文件名</param>
        /// <param name="df">导出List数据集合</param>
        /// <param name="strHeaderText">excel文本标题</param>
        public DownloadFileExcelHeader(string[] cellNames, string pFileName, IList df, string strHeaderText)
        {

            fileName = pFileName;
            
            //普通单元格样式
            ICellStyle cellstyle = book.CreateCellStyle();
            cellstyle.Alignment = HorizontalAlignment.Left; //水平居左
            cellstyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
            cellstyle.WrapText = false; //自动换行
            IFont cellfont = book.CreateFont();
            cellfont.FontHeightInPoints = 10; //11号字体
            cellstyle.SetFont(cellfont);
            //列表头单元格样式
            ICellStyle cellheadstyle = book.CreateCellStyle();
            cellheadstyle.Alignment = HorizontalAlignment.Center;
            cellheadstyle.VerticalAlignment = VerticalAlignment.Center;
            IFont cellheadfont = book.CreateFont();
            cellheadfont.FontHeightInPoints = 10;
            cellheadfont.Boldweight = (short)FontBoldWeight.None; //字体是否加粗
            cellheadstyle.SetFont(cellheadfont);
            //船名航次
            ICellStyle VesselVoystyle = book.CreateCellStyle();
            VesselVoystyle.Alignment = HorizontalAlignment.Left;
            VesselVoystyle.VerticalAlignment = VerticalAlignment.Bottom;
            VesselVoystyle.WrapText = true; //自动换行
            IFont VesselVoyfont = book.CreateFont();
            VesselVoyfont.FontHeightInPoints = 10;
            VesselVoyfont.Boldweight = (short)FontBoldWeight.Bold; //字体是否加粗
            VesselVoystyle.SetFont(VesselVoyfont);

            DataTable grid = ToDataTableTow(df);
            ISheet sheet = book.CreateSheet(System.IO.Path.GetFileNameWithoutExtension(pFileName));
            sheet.IsPrintGridlines = true; //打印时显示网格线
            sheet.DisplayGridlines = true;//查看时显示网格线
            //sheet.DefaultRowHeightInPoints = 25; 这种默认设置不起作用
            //sheet.SetColumnWidth(0, 20 * 256);//预订人宽度                
            sheet.DefaultColumnWidth = 18;
            int rowIndex = 2;//开始添加数据的行数
            int colIndex = 0;
            //int vesIndex = 0;
            //excel文本标题
            HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);
            headerRow.HeightInPoints = 25;
            headerRow.CreateCell(0).SetCellValue(strHeaderText);
            //excel文本标题样式
            HSSFCellStyle headStyle = (HSSFCellStyle)book.CreateCellStyle();
            headStyle.Alignment = HorizontalAlignment.Center;
            HSSFFont font = (HSSFFont)book.CreateFont();
            font.FontHeightInPoints = 18;
            font.Boldweight = 500;
            headStyle.SetFont(font);
            headerRow.GetCell(0).CellStyle = headStyle;
            sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, cellNames.Length - 1));
            

            //设置
            IRow row = sheet.CreateRow(1);
            row.HeightInPoints = 18;
         
            //列标题
            for (int i = 0; i < cellNames.Length; i++)
            {
                ICell cell = row.CreateCell(colIndex);
                cell.SetCellValue(cellNames[i].ToString());
                cell.CellStyle = cellheadstyle;
                colIndex++;
            }
            //导入数据行
            foreach (DataRow rows in grid.Rows)
            {
                colIndex = 0;
                row = sheet.CreateRow(rowIndex);
                foreach (DataColumn col in grid.Columns)
                {
                    ICell cell = row.CreateCell(colIndex);
                    cell.SetCellValue(rows[col.ColumnName].ToString());
                    cell.CellStyle = cellstyle;
                    colIndex++;
                }
                rowIndex++;
            }

        }

        /// <summary>
        /// 将集合类转换成DataTable    
        /// </summary>    
        /// <returns></returns>  
        public static DataTable ToDataTableTow(IList list)
        {
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();

                foreach (PropertyInfo pi in propertys)
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }
                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }
        /// <summary>
        /// 重写返回方法
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            bool isFireFox = false;
            if (HttpContext.Current.Request.ServerVariables["http_user_agent"].ToLower().IndexOf("firefox") != -1)
            {
                isFireFox = true;
            }    
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            byte[] bytes = ms.ToArray();
            book = null;
            ms.Close();
            ms.Dispose();
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //通知浏览器下载文件而不是打开
            if (isFireFox == true)
            {
                fileName = "\"" + fileName + "\"";
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            }
            else
            {
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString());
            }  
            //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            HttpContext.Current.Response.BinaryWrite(bytes);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();

        }

          
    }

总:如果没有from事件,会出现点击导出按钮没效果

/// <summary> /// 导出Excel /// </summary> /// <param name="table"></param> /// <returns></returns> public bool ToExcel(DataTable table) { FileStream fs = new FileStream(this._filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); IWorkbook workBook = new HSSFWorkbook(); this._sheetName = this._sheetName.IsEmpty() ? "sheet1" : this._sheetName; ISheet sheet = workBook.CreateSheet(this._sheetName); //处理表格标题 IRow row = sheet.CreateRow(0); row.CreateCell(0).SetCellValue(this._title); sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, table.Columns.Count - 1)); row.Height = 500; ICellStyle cellStyle = workBook.CreateCellStyle(); IFont font = workBook.CreateFont(); font.FontName = "微软雅黑"; font.FontHeightInPoints = 17; cellStyle.SetFont(font); cellStyle.VerticalAlignment = VerticalAlignment.Center; cellStyle.Alignment = HorizontalAlignment.Center; row.Cells[0].CellStyle = cellStyle; //处理表格列头 row = sheet.CreateRow(1); for (int i = 0; i < table.Columns.Count; i++) { row.CreateCell(i).SetCellValue(table.Columns[i].ColumnName); row.Height = 350; sheet.AutoSizeColumn(i); } //处理数据内容 for (int i = 0; i < table.Rows.Count; i++) { row = sheet.CreateRow(2 + i); row.Height = 250; for (int j = 0; j < table.Columns.Count; j++) { row.CreateCell(j).SetCellValue(table.Rows[i][j].ToString()); sheet.SetColumnWidth(j, 256 * 15); } } //写入数据流 workBook.Write(fs); fs.Flush(); fs.Close(); return true; } /// <summary> /// 导出Excel /// </summary> /// <param name="table"></param> /// <param name="title"></param> /// <param name="sheetName"></param> /// <returns></returns> public bool ToExcel(DataTable table, string title, string sheetName, string filePath) { this._title = title; this._sheetName = sheetName; this._filePath = filePath; return ToExcel(table); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

润小仙女

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值