运用NPOI,反射导出EXCEL。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了运用NPOI,反射导出EXCEL。相关的知识,希望对你有一定的参考价值。

首先我用的是MVC,EF框架,保证查询出来的数据结构如以下结构

            var data = list.Select(ps => new
            {
                SKU = ps.ProductCode,
                中文名称 = ps.Product.Name,
                所属公司 = ps.Company.CompanyName,
            }).ToList();

调用方法:

 var excelStr = Service.GetExcelOutStr(data);

实现方法:

 /// <summary>
        /// 导出数据(李老师)
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="objList">集合</param>
        /// <returns>MemoryStream流</returns>
        public MemoryStream GetExcelOutStr<T>(List<T> objList)
        {
            if (objList == null
                || !objList.Any())
            {
                return null;
            }

            DataTable table = new DataTable();
            

            Type myType = objList[0].GetType();
            //根据反射从传递进来的属性名信息得到要显示的属性 
            var properties = myType.GetProperties();
            foreach (var pro in properties)
            {
                table.Columns.Add(pro.Name, typeof(string));
            } 
            List<System.Reflection.PropertyInfo> myPro = new List<System.Reflection.PropertyInfo>();
            foreach (DataColumn col in table.Columns)
            {
                System.Reflection.PropertyInfo p = myType.GetProperty(col.ColumnName);
                if (p != null)
                {
                    myPro.Add(p);
                }
            }
            foreach (T obj in objList)
            {
                DataRow row = table.NewRow();

                foreach (System.Reflection.PropertyInfo p in myPro)
                {
                    var value = p.GetValue(obj, null);
                    row[p.Name] = value;
                }
                table.Rows.Add(row);
            }
            return ExcelHelper.Export(table, "");
        }

使用NPOI将table导出到excel:

 /// <summary>
        /// DataTable导出到Excel的MemoryStream
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表头文本</param>
        public static MemoryStream Export(DataTable dtSource, string strHeaderText)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            var sheet = workbook.CreateSheet();
            //创建样式1。
            ICellStyle ccs = workbook.CreateCellStyle();
            ccs.VerticalAlignment = VerticalAlignment.Center;
            //创建样式2
            ICellStyle cs = workbook.CreateCellStyle();
            cs.WrapText = true;
            #region 右击文件 属性信息
            {
                DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                dsi.Company = "epc";
                workbook.DocumentSummaryInformation = dsi;

                SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                si.Author = "epc.oa.system"; //填加xls文件作者信息
                si.ApplicationName = "oa"; //填加xls文件创建程序信息
                si.LastAuthor = ""; //填加xls文件最后保存者信息
                si.Comments = ""; //填加xls文件作者信息
                si.Title = "数据导出"; //填加xls文件标题信息
                si.Subject = "数据导出";//填加文件主题信息
                si.CreateDateTime = DateTime.Now;
                workbook.SummaryInformation = si;
            }
            #endregion

            var dateStyle = workbook.CreateCellStyle();
            var format = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            //取得列宽
            int[] arrColWidth = new int[dtSource.Columns.Count];
            foreach (DataColumn item in dtSource.Columns)
            {
                arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
            }
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (intTemp > arrColWidth[j])
                    {
                        arrColWidth[j] = intTemp;
                    }
                }
            }
            int rowIndex = 0;
            foreach (DataRow row in dtSource.Rows)
            {
                #region 新建表,填充表头,填充列头,样式
                if (rowIndex == 65535 || rowIndex == 0)
                {
                    if (rowIndex != 0)
                    {
                        sheet = workbook.CreateSheet();
                    }
                    #region 列头及样式
                    {
                        var headerRow = sheet.CreateRow(0);
                        var headStyle = workbook.CreateCellStyle();
                        //   headStyle.Alignment = CellHorizontalAlignment.CENTER;
                        var font = workbook.CreateFont();
                        font.FontHeightInPoints = 10;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);
                        foreach (DataColumn column in dtSource.Columns)
                        {
                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                            //headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
                            ////设置列宽
                            //sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
                        }
                        headerRow = null;
                    }
                    #endregion
                    rowIndex = 1;
                }
                #endregion


                #region 填充内容
                var dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    var newCell = dataRow.CreateCell(column.Ordinal);
                    string drValue = row[column].ToString();
                    dataRow.GetCell(column.Ordinal).CellStyle = ccs;
                    if (drValue.Contains("\n"))
                    {
                        var h = drValue.Count(t => t == \n) + 1;

                        dataRow.GetCell(column.Ordinal).CellStyle = cs;
                        dataRow.HeightInPoints = h * sheet.DefaultRowHeight / 20;
                    }
                    switch (column.DataType.ToString())
                    {
                        case "System.String"://字符串类型
                            newCell.SetCellValue(drValue);
                            break;
                        case "System.DateTime"://日期类型
                            DateTime dateV;
                            DateTime.TryParse(drValue, out dateV);
                            newCell.SetCellValue(dateV);

                            newCell.CellStyle = dateStyle;//格式化显示
                            break;
                        case "System.Boolean"://布尔型
                            bool boolV = false;
                            bool.TryParse(drValue, out boolV);
                            newCell.SetCellValue(boolV);
                            break;
                        case "System.Int16"://整型
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV = 0;
                            int.TryParse(drValue, out intV);
                            newCell.SetCellValue(intV);
                            break;
                        case "System.Decimal"://浮点型
                        case "System.Double":
                            double doubV = 0;
                            double.TryParse(drValue, out doubV);
                            newCell.SetCellValue(doubV);
                            break;
                        case "System.DBNull"://空值处理
                            newCell.SetCellValue("");
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;
                    }

                }
                #endregion

                rowIndex++;
            }

            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                workbook = null;
                sheet = null;
                return ms;
            }
        }

 

以上是关于运用NPOI,反射导出EXCEL。的主要内容,如果未能解决你的问题,请参考以下文章

.Net Core+NPOI快速导入导出Excel

NPOI导出excel(带图片)

c#使用NPOI进行Excel导入导出,附源码,vs2010

NPOI 导出 excel 性能测试

NPOI Excel导出数据信息

NPOI的excel导出1