惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
Webroot Blog
Webroot Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
Threat Research - Cisco Blogs
V2EX - 技术
V2EX - 技术
L
LINUX DO - 热门话题
Google DeepMind News
Google DeepMind News
Recorded Future
Recorded Future
S
Schneier on Security
I
InfoQ
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
The GitHub Blog
The GitHub Blog
S
Security @ Cisco Blogs
O
OpenAI News
W
WeLiveSecurity
Vercel News
Vercel News
阮一峰的网络日志
阮一峰的网络日志
Simon Willison's Weblog
Simon Willison's Weblog
人人都是产品经理
人人都是产品经理
Cloudbric
Cloudbric
The Last Watchdog
The Last Watchdog
The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
NISL@THU
NISL@THU
T
Tailwind CSS Blog
V
Visual Studio Blog
PCI Perspectives
PCI Perspectives
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Jina AI
Jina AI
D
DataBreaches.Net
B
Blog RSS Feed
N
News and Events Feed by Topic
N
News and Events Feed by Topic
H
Heimdal Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
腾讯CDC
Latest news
Latest news
V
Vulnerabilities – Threatpost
Hacker News: Ask HN
Hacker News: Ask HN
WordPress大学
WordPress大学
V
V2EX
aimingoo的专栏
aimingoo的专栏
博客园 - 司徒正美
Apple Machine Learning Research
Apple Machine Learning Research
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Register - Security
The Register - Security
Help Net Security
Help Net Security

博客园 - 曾伟

不干胶、热敏打印 wpf 滚屏数据显示 net core quartz调度 warp打包 nssm部署到windowsservice c# webapi 过滤器token、sign认证、访问日志 c# ini文件操作 WCF多种调用方式兼容 网页打印javascript:window.print() window.showModalDialog弹出对话框刷新问题 ASP.NET] 选择文件夹的对话框 常用SQL语句书写技巧 控制同一exe程序打开多次 - 曾伟 - 博客园 IIS6 MMC检测到此管理单元发生一个错误,建议您关闭并重新启动mmc 在上传文件时限制上传文件的大小,并捕捉超过文件大小限制的 - 曾伟 - 博客园 Lucene的例子 javascript 获取标签具体位置 - 曾伟 - 博客园 JavaScript实现类,有多种方法。 Javascript实现截图功能(代码) 终端服务器超出了最大允许连接数 DBCC CHECKDB 数据库或表修复
c# NPOI文件操作
曾伟 · 2019-06-05 · via 博客园 - 曾伟
public static Byte[] RenderDataToExcel<T>(List<T> SourceList, List<String> filter) where T : new()
        {
            XSSFWorkbook workbook = null;
            MemoryStream ms = null;
            ISheet sheet = null;
            XSSFRow headerRow = null;
            try
            {
                workbook = new XSSFWorkbook();
                ms = new MemoryStream();
                sheet = workbook.CreateSheet();
                headerRow = (XSSFRow)sheet.CreateRow(0);

                PropertyInfo[] arrProperty = RemoveFilterColumn<T>(filter);
                
                PropertyInfo pi = null;
                for (int i = 0; i < arrProperty.Length; i++)
                {
                    pi = arrProperty[i];
                    headerRow.CreateCell(i).SetCellValue(GetPropertyDescription(pi));
                }

                int rowIndex = 1;
                for (int i = 0; i < SourceList.Count; i++)
                {
                    XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
                    for (int j = 0; j < arrProperty.Length; j++)
                    {
                        pi = arrProperty[j];
                        object piValue = pi.GetValue(SourceList[i], null);
                        if (piValue == null)
                        {
                            dataRow.CreateCell(j).SetCellValue("");
                            continue;
                        }
                        Type pitype = pi.PropertyType;
                        if (pitype.Name.ToLower().Contains("nullable"))
                        {
                            pitype = Nullable.GetUnderlyingType(pitype);
                        }
                        //var rowNumberAttr = pi.GetCustomAttributes(typeof(Attribute), false);
                        //if (rowNumberAttr != null && rowNumberAttr.Length > 0)
                        //{
                        //    dataRow.CreateCell(j).SetCellValue((i + 1).ToString());
                        //    continue;
                        //}
                        if (pitype == typeof(bool))
                        {
                            dataRow.CreateCell(j).SetCellValue(Convert.ToBoolean(piValue) ? "" : "");
                            continue;
                        }
                        if (pitype.IsEnum)
                        {
                            dataRow.CreateCell(j).SetCellValue(EnumHelper.GetDescription(pitype, Convert.ToInt32(piValue)));
                            continue;
                        }
                        if (pitype == typeof(DateTime)
                            || pitype == typeof(DateTime?))
                        {
                            //var showDateTimeAttr = pi.GetCustomAttributes(typeof(DateTimeFormatAttribute), false);
                            //if (showDateTimeAttr != null && showDateTimeAttr.Length > 0)
                            //{
                            //    DateTime nowtime = DateTime.Parse(piValue.ToString());
                            //    arrData[i + 1, j] = nowtime.ToString((showDateTimeAttr[0] as DateTimeFormatAttribute).DataFormatString);
                            //    continue;
                            //}

                            //default datetime showformater
                            dataRow.CreateCell(j).SetCellValue(DateTime.Parse(piValue.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                            continue;
                        }
                        dataRow.CreateCell(j).SetCellValue(piValue.ToString());
                    }
                    ++rowIndex;
                }
                //列宽自适应,只对英文和数字有效 这个动作比较耗时间
                //for (int i = 0; i <= arrProperty.Length; ++i)
                //    sheet.AutoSizeColumn(i);
                workbook.Write(ms);
                ms.Flush();
                return ms.ToArray();
            }
            catch (Exception ex)
            {
                Log.loggeremail.Error("RenderDataTableToExcel Exception:"+ex.Message);
                return null;
            }
            finally
            {
                ms.Close();
                sheet = null;
                headerRow = null;
                workbook = null;
            }
        }

        public static void SaveListToExcel<T>(List<T> SourceList, List<String> filter, string filePath) where T : new()
        {
            XSSFWorkbook workbook = null;
            ISheet sheet = null;
            XSSFRow headerRow = null;
            try
            {
                workbook = new XSSFWorkbook();
                sheet = workbook.CreateSheet();
                headerRow = (XSSFRow)sheet.CreateRow(0);

                PropertyInfo[] arrProperty = RemoveFilterColumn<T>(filter);

                PropertyInfo pi = null;
                for (int i = 0; i < arrProperty.Length; i++)
                {
                    pi = arrProperty[i];
                    headerRow.CreateCell(i).SetCellValue(GetPropertyDescription(pi));
                }

                int rowIndex = 1;
                for (int i = 0; i < SourceList.Count; i++)
                {
                    XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
                    for (int j = 0; j < arrProperty.Length; j++)
                    {
                        pi = arrProperty[j];
                        object piValue = pi.GetValue(SourceList[i], null);
                        if (piValue == null)
                        {
                            dataRow.CreateCell(j).SetCellValue("");
                            continue;
                        }
                        Type pitype = pi.PropertyType;
                        if (pitype.Name.ToLower().Contains("nullable"))
                        {
                            pitype = Nullable.GetUnderlyingType(pitype);
                        }
                        //var rowNumberAttr = pi.GetCustomAttributes(typeof(Attribute), false);
                        //if (rowNumberAttr != null && rowNumberAttr.Length > 0)
                        //{
                        //    dataRow.CreateCell(j).SetCellValue((i + 1).ToString());
                        //    continue;
                        //}
                        if (pitype == typeof(bool))
                        {
                            dataRow.CreateCell(j).SetCellValue(Convert.ToBoolean(piValue) ? "" : "");
                            continue;
                        }
                        if (pitype.IsEnum)
                        {
                            dataRow.CreateCell(j).SetCellValue(EnumHelper.GetDescription(pitype, Convert.ToInt32(piValue)));
                            continue;
                        }
                        if (pitype == typeof(DateTime)
                            || pitype == typeof(DateTime?))
                        {
                            //var showDateTimeAttr = pi.GetCustomAttributes(typeof(DateTimeFormatAttribute), false);
                            //if (showDateTimeAttr != null && showDateTimeAttr.Length > 0)
                            //{
                            //    DateTime nowtime = DateTime.Parse(piValue.ToString());
                            //    arrData[i + 1, j] = nowtime.ToString((showDateTimeAttr[0] as DateTimeFormatAttribute).DataFormatString);
                            //    continue;
                            //}

                            //default datetime showformater
                            dataRow.CreateCell(j).SetCellValue(DateTime.Parse(piValue.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                            continue;
                        }
                        dataRow.CreateCell(j).SetCellValue(piValue.ToString());
                    }
                    ++rowIndex;
                }
                //列宽自适应,只对英文和数字有效 这个动作比较耗时间
                //for (int i = 0; i <= arrProperty.Length; ++i)
                //    sheet.AutoSizeColumn(i);

                using (var file = new FileStream(filePath, FileMode.Create))
                {
                    workbook.Write(file);
                    file.Close();
                    file.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sheet = null;
                headerRow = null;
                workbook = null;
            }
        }

        /// <summary>
        /// 创建一个excel
        /// </summary>
        /// <returns></returns>
        public static XSSFWorkbook CreateXSSFWorkbook()
        {
            XSSFWorkbook xssfworkbook = new XSSFWorkbook();
            return xssfworkbook;
        }

        /// <summary>
        /// 创建一个sheet
        /// </summary>
        /// <param name="hssfworkbook">excel</param>
        /// <param name="sheetName">sheet名称</param>
        /// <param name="isFreezePane">是否存在冻结</param>
        /// <param name="colSplit"></param>
        /// <param name="rowSplit">行数</param>
        /// <param name="leftmostColumn"></param>
        /// <param name="topRow">顶上N行</param>
        /// <returns></returns>
        public static ISheet CreateSheet(XSSFWorkbook xssfworkbook, string sheetName, bool isFreezePane = false, int colSplit = 0, int rowSplit = 0, int leftmostColumn = 0, int topRow = 0)
        {
            ISheet sheet1 = xssfworkbook.CreateSheet(sheetName);

            if (isFreezePane)
            {
                sheet1.CreateFreezePane(colSplit, rowSplit, leftmostColumn, topRow);
            }

            return sheet1;
        }

        public static IRow CreateRow(ISheet sheet, int rowIndex)
        {
            IRow row = sheet.CreateRow(rowIndex);
            return row;
        }

        public static ICell CreateCell(XSSFWorkbook xssfworkbook, IRow row, int cellIndex, string cellValue, bool isLock = true)
        {
            ICell cell = row.CreateCell(cellIndex);
            cell.SetCellValue(cellValue);
            //加锁
            var locked = xssfworkbook.CreateCellStyle();
            locked.IsLocked = isLock;
            cell.CellStyle = locked;

            return cell;
        }

        public static ICellStyle LockedRow(XSSFWorkbook xssfworkbook)
        {
            var locked = xssfworkbook.CreateCellStyle();
            locked.IsLocked = true;
            return locked;
        }

        public static ICellStyle UnLockedRow(XSSFWorkbook xssfworkbook)
        {
            var locked = xssfworkbook.CreateCellStyle();
            locked.IsLocked = false;
            return locked;
        }

        /// <summary>
        /// 获取单元格样式
        /// </summary>
        /// <param name="hssfworkbook">Excel操作类</param>
        /// <param name="font">单元格字体</param>
        /// <param name="fillForegroundColor">图案的颜色</param>
        /// <param name="fillPattern">图案样式</param>
        /// <param name="fillBackgroundColor">单元格背景</param>
        /// <param name="ha">垂直对齐方式</param>
        /// <param name="va">垂直对齐方式</param>
        /// <returns></returns>
        public static ICellStyle GetCellStyle(XSSFWorkbook hssfworkbook, IFont font, HSSFColor fillForegroundColor, FillPattern fillPattern, HSSFColor fillBackgroundColor, NPOI.SS.UserModel.HorizontalAlignment ha, VerticalAlignment va, bool hasBorder)
        {
            ICellStyle cellstyle = hssfworkbook.CreateCellStyle();
            cellstyle.FillPattern = fillPattern;
            cellstyle.Alignment = ha;
            cellstyle.VerticalAlignment = va;
            if (fillForegroundColor != null)
            {
                cellstyle.FillForegroundColor = fillForegroundColor.Indexed;
            }
            if (fillBackgroundColor != null)
            {
                cellstyle.FillBackgroundColor = fillBackgroundColor.Indexed;
            }
            if (font != null)
            {
                cellstyle.SetFont(font);
            }
            if (hasBorder)
            {
                //有边框
                cellstyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                cellstyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                cellstyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                cellstyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            }
            return cellstyle;
        }

        /// <summary>
        /// 合并单元格
        /// </summary>
        /// <param name="sheet">要合并单元格所在的sheet</param>
        /// <param name="rowstart">开始行的索引</param>
        /// <param name="rowend">结束行的索引</param>
        /// <param name="colstart">开始列的索引</param>
        /// <param name="colend">结束列的索引</param>
        public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend)
        {
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend);
            sheet.AddMergedRegion(cellRangeAddress);
        }

        /// <summary>
        /// 建立下拉,验证数据有效性
        /// </summary>
        /// <param name="hssfworkbook"></param>
        /// <param name="sheet"></param>
        /// <param name="firstRow"></param>
        /// <param name="lastRow"></param>
        /// <param name="firstCol"></param>
        /// <param name="lastCol"></param>
        /// <param name="refersToFormula"></param>
        /// <param name="XSSFName"></param>
        public static void SetValidationData(XSSFWorkbook hssfworkbook, ISheet sheet, int firstRow, int lastRow, int firstCol, int lastCol, string refersToFormula, string XSSFName)
        {
            //数据有效性 下拉
            XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet as XSSFSheet);
            //位置
            CellRangeAddressList regions = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);

            XSSFName range = (XSSFName)hssfworkbook.CreateName();
            range.RefersToFormula = refersToFormula;
            range.NameName = XSSFName;
            XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint)dvHelper.CreateFormulaListConstraint(XSSFName);

            XSSFDataValidation dataValidate = (XSSFDataValidation)dvHelper.CreateValidation(dvConstraint, regions);
            sheet.AddValidationData(dataValidate);
        }
List<String> filter = new List<string>();
filter.Add("LableBatchNo");//过滤列
byte[] byteList = ExcelHelper.RenderToExcel<SecurityLabelModel>(allList, filter);
MemoryStream stream = new MemoryStream(byteList);
                stream.Seek(0, 0);

                return new FileStreamResult(stream, "application/vnd.ms-excel") { FileDownloadName = HttpUtility.UrlPathEncode(名称 + DateTime.Now.ToString("yyyyMMddHHmmssfff") + 后缀) };