在MVC中,用NPOI 导出Excel

公用导出excel类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.HSSF;
using NPOI.XSSF;
using NPOI.SS.UserModel;   
public class ExportExcel
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T">数据实体</typeparam>
        /// <param name="title">标题</param>
        /// <param name="objList">数据</param>
        /// <param name="NameDictionary">excel表头</param>
        /// <returns>MemoryStream</returns>
        public static System.IO.MemoryStream Method_One<T>(string title, List<T> objList, Dictionary<string, string> NameDictionary)
        {
            NPOI.SS.UserModel.IWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("Sheet1");
            NPOI.SS.UserModel.IRow row;
            NPOI.SS.UserModel.ICell cell;
            NPOI.SS.UserModel.ICellStyle cellStyle;

            int rowNum = 0;

            if (!string.IsNullOrEmpty(title))
            {
                #region 标题
                #region 标题样式
                cellStyle = workbook.CreateCellStyle();
                cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//垂直居中有问题
                NPOI.SS.UserModel.IFont font = workbook.CreateFont();
                font.FontHeightInPoints = 15;
                cellStyle.SetFont(font);
                #endregion
                row = sheet.CreateRow(rowNum);
                cell = row.CreateCell(0, NPOI.SS.UserModel.CellType.String);
                cell.SetCellValue(title);
                cell.CellStyle = cellStyle;
                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, NameDictionary.Count));
                rowNum++;
                #endregion
            }

            if (objList.Count > 0)
            {
                Type type = objList[0].GetType();
                if (type != null)
                {
                    System.Reflection.PropertyInfo[] properties = type.GetProperties();
                    if (properties.Length > 0)
                    {
                        #region 表头
                        #region 表头样式
                        cellStyle = workbook.CreateCellStyle();
                        cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;

                        #endregion
                        if (NameDictionary.Count > 0)
                        {
                            row = sheet.CreateRow(rowNum);
                            int count = 0;
                            cell = row.CreateCell(count, NPOI.SS.UserModel.CellType.String);
                            cell.SetCellValue("行号");
                            cell.CellStyle = cellStyle;

                            count++;
                            for (int m = 0; m < properties.Length; m++)
                            {
                                if (NameDictionary.ContainsKey(properties[m].Name))
                                {
                                    cell = row.CreateCell(count, NPOI.SS.UserModel.CellType.String);
                                    string displayName = GetDisplayNameByPropertyName(properties[m].Name, NameDictionary);
                                    cell.SetCellValue(displayName == null ? "" : displayName);
                                    cell.CellStyle = cellStyle;
                                    count++;
                                }
                            }
                            rowNum++;
                        }
                        #endregion

                        #region 表体
                        if (NameDictionary.Count > 0)
                        {
                            int rowNumber = 1;
                            for (int i = 0; i < objList.Count; i++)
                            {
                                row = sheet.CreateRow(i + rowNum);
                                int count = 0;
                                cell = row.CreateCell(count, NPOI.SS.UserModel.CellType.String);
                                cell.SetCellValue(rowNumber);
                                cell.CellStyle = cellStyle;
                                count++;
                                for (int j = 0; j < properties.Length; j++)
                                {
                                    if (NameDictionary.ContainsKey(properties[j].Name))
                                    {
                                        cell = row.CreateCell(count);
                                        object obj = properties[j].GetValue(objList[i]);
                                        cell.SetCellValue(obj == null ? "" : obj.ToString());
                                        cell.CellStyle = cellStyle;
                                        count++;
                                    }
                                }
                                rowNumber++;
                            }
                        }
                        #endregion
                    }
                }
            }
            AutoColumnWidth(sheet, NameDictionary.Count + 1);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            workbook.Write(ms);
            return ms;
        }
        private static string GetDisplayNameByPropertyName(string propertyName, Dictionary<string, string> NameDictionary)
        {
            string result = null;
            foreach (KeyValuePair<string, string> dic in NameDictionary)
            {
                if (dic.Key == propertyName)
                {
                    result = dic.Value;
                }
                continue;
            }
            return result;
        }
        private static void AutoColumnWidth(ISheet sheet, int cols)
        {
            for (int col = 0; col <= cols; col++)
            {
                sheet.AutoSizeColumn(col);//自适应宽度,但是其实还是比实际文本要宽
                int columnWidth = sheet.GetColumnWidth(col) / 256;//获取当前列宽度
                for (int rowIndex = 1; rowIndex <= sheet.LastRowNum; rowIndex++)
                {
                    IRow row = sheet.GetRow(rowIndex);
                    ICell cell = row.GetCell(col);
                    if (cell != null)
                    {
                        int contextLength = Encoding.UTF8.GetBytes(cell.ToString()).Length;//获取当前单元格的内容宽度
                        columnWidth = columnWidth < contextLength ? contextLength : columnWidth;
                    }
                    else { columnWidth = 100; }

                }
                sheet.SetColumnWidth(col, columnWidth * 200);

            }
        }

    }

MVC测试类 

 /// <summary>
        /// 核查超时率统计
        /// </summary>
        /// <param name="OrgNO"></param>
        /// <param name="TypeNO"></param>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public ActionResult ExportExcelGetCountTable2(string OrgNO, string TypeNO, string BeginTime, string EndTime)
        {
            Dictionary<string, string> listHead = new Dictionary<string, string>();
            listHead.Add("OrgName", "单位名称");
            listHead.Add("t1", "预警总数");
            listHead.Add("t2", "核查超时数");
            listHead.Add("t4", "核查超时率");
            var listCountTable2 = BizContext.GetSqlTextList<TotalTable>("ALM_CountTable2_pro",
                new
                {
                    OrgNO = OrgNO == "" ? null : OrgNO,
                    TypeNO = TypeNO == "-1" ? null : TypeNO,
                    BeginTime = BeginTime == "" ? null : BeginTime,
                    EndTime = EndTime == "" ? null : EndTime,
                }, VideoConnectionKind.Reader, CommandType.StoredProcedure);
            return File(Core.Excel.ExportExcel.Method_One<TotalTable>("核查超时率", listCountTable2, listHead).ToArray(), "application/vnd.ms-excel", "核查超时率统计" + OrgNO + ".xls");
        }

实体类

/// <summary>
    /// 预警统计表格
    /// </summary>
    public class TotalTable
    {
        public string OrgNO { get; set; }
        public string OrgName { get; set; }
        public string t1 { get; set; }
        public string t2 { get; set; }
        public string t3 { get; set; }
        public string t4 { get; set; }
        public string t5 { get; set; }
    }

前台代码

<div style='float:right;margin-botton:5px;'><button type='button' class='btn btn-default' onclick='ExcelExportCountTable2()'>导出</button></div>

Click代码

function ExcelExportCountTable2() {
    window.location.href = "/AlarmTotal/ExportExcelGetCountTable2?OrgNO=" + $('#OrgTree').combotree('getValue') + "&TypeNO=" + $('#typeTree').combotree('getValue') + "&BeginTime=" + getMonth(true) + "&EndTime=" + getMonth(false) + "";
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值