NPOI 简单使用

Posted liyiboke

tags:

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

[AttributeUsage(AttributeTargets.All)]
    public class DataTableConvertAttribute : Attribute
    {
        public DataTableConvertAttribute(bool exclusde)
        {
            this._exclusde = exclusde;
        }

        bool _exclusde;
        public bool Exclusde
        {
            get
            {
                return _exclusde;
            }
        }
    }

    public class NPOITest
    {
        public ActionResult Test_001()
        {
            var stream = NPOIHelp.Export(new List<SheetSection>() { });
            var fileDownloadName = String.Format("{0}-明细{1}.xlsx", "导出名称", DateTime.Now.ToString("yyyyMMdd"));
            return File(stream, "application/vnd.ms-excel", Url.Encode(fileDownloadName).Replace("+", "%20"));
        }
        public ActionResult Test_002()
        {
            return File(NPOIHelp.Export(new List<Items>() { }, "内容,备注"), "application/vnd.ms-excel", Url.Encode("信息明细.xls"));
        }
    }
    public static class NPOIHelp
    {
        /// <summary>
        /// NPOI 根据模板 下载数据
        /// </summary>
        /// <param name="section">数据集合</param>
        /// <returns></returns>
        public static MemoryStream Export(ICollection<SheetSection> section)
        {
            MemoryStream ms = new MemoryStream();

            IWorkbook hssfworkbookDown;

            using (FileStream file = new FileStream(HttpContext.Current.Server.MapPath("~/Content/导入模板.xlsx"), FileMode.Open, FileAccess.Read))
            {
                hssfworkbookDown = WorkbookFactory.Create(file);

                file.Close();
            }

            ISheet sheet1 = hssfworkbookDown.GetSheetAt(0);

            //向上移动模板数据达到隐藏效果
            for (int i = sheet1.LastRowNum - 1; i >= 1 + 1; i--)
            {
                sheet1.ShiftRows(i, i + 1, -1);
            }

            IRow row;
            ICell cell;
            int rowIndex = 1;
            int colIndex = 0;

            //开始向excel表格中写入数据
            if (section.Count() > 0)
            {
                foreach (var item in section)
                {
                    colIndex = 0;
                    row = sheet1.CreateRow(rowIndex);

                    sheet1.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(rowIndex, rowIndex + item.Items.Count() - 1, colIndex, colIndex));

                    //集合名称
                    cell = row.CreateCell(colIndex);
                    cell.SetCellValue(item.Name);

                    foreach (var sheetItem in item.Items)
                    {
                        //子集合内容
                        cell = row.CreateCell(colIndex + 1);
                        cell.SetCellValue(sheetItem.Content);

                        //子集合备注
                        cell = row.CreateCell(colIndex + 2);
                        cell.SetCellValue(sheetItem.Remark);

                        row = sheet1.CreateRow(++rowIndex);
                    }
                    if (item.Items.Count() == 0)
                        rowIndex++;
                }
            }
            else
            {
                var r = sheet1.GetRow(rowIndex);
                sheet1.RemoveRow(r);
            }

            hssfworkbookDown.Write(ms);
            ms.Flush();
            ms.Position = 0;
            hssfworkbookDown = null;

            return ms;
        }

        /// <summary>
        /// 根据数据集合+指定的表头导出数据
        /// </summary>
        /// <typeparam name="T">任意类型</typeparam>
        /// <param name="data">数据集合</param>
        /// <param name="strHeaderText">"内容,备注"</param>
        /// <returns></returns>
        public static MemoryStream Export<T>(IList<T> data, string strHeaderText)
        {
            var dtSource = ToDataTable(data);
            var tuple = Tuple.Create(String.Empty, strHeaderText, dtSource);

            return Export(tuple);
        }
        public static DataTable ToDataTable<T>(IList<T> data)
        {
            var properties = TypeDescriptor.GetProperties(typeof(T));
            var filtered = new List<PropertyDescriptor>();
            var dt = new DataTable();

            for (int i = 0; i < properties.Count; i++)
            {
                var property = properties[i];
                var attribute = property.Attributes[typeof(DataTableConvertAttribute)] as DataTableConvertAttribute;

                if (!(null != attribute && attribute.Exclusde))
                {
                    filtered.Add(property);
                    dt.Columns.Add(property.Name, property.PropertyType);
                }
            }

            object[] values = new object[filtered.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = filtered[i].GetValue(item);
                }
                dt.Rows.Add(values);
            }
            return dt;
        }
        public static MemoryStream Export(params Tuple<string, string, DataTable>[] tuples)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();

            if (null != tuples && tuples.Length > 0)
            {
                tuples.ForEach(tuple =>
                {
                    FillHeaderAndContent(workbook, tuple.Item1, tuple.Item2, tuple.Item3);
                });
            }

            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;

            return ms;
        }
    }

    /// <summary>
    /// 数据集合
    /// </summary>
    public class SheetSection
    {
        public string Name { get; set; }
        public ICollection<Items> Items { get; set; }
    }

    /// <summary>
    /// 数据集合内部子集
    /// </summary>
    public class Items
    {
        /// <summary>
        /// 内容
        /// </summary>
        public string Content { get; set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string Remark { get; set; }
    }

 

以上是关于NPOI 简单使用的主要内容,如果未能解决你的问题,请参考以下文章

Npoi简单读写Excel

NPOI 简单使用

NPOI导出excel

C#里使用NPOI创建EXCEL文件的简单方法

C#里使用NPOI创建EXCEL文件的简单方法

C#里使用NPOI创建EXCEL文件的简单方法