zoukankan      html  css  js  c++  java
  • 使用 NPOI 将数据导出至 Excel 中(可以创建多个工作表)

    类:

        public class Excel
        {
            private FileStream fs = null;
            private XSSFWorkbook workbook = null;
    
            public Excel(string path, string fileName)
            {
                if(!path.EndsWith(@""))
                {
                    path = path + "\";
                }
    
                //如果文件夹不存在,则创建该文件夹
                if(!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
    
                if(!fileName.EndsWith(".xlsx") && !fileName.EndsWith(".xls"))
                {
                    fileName = fileName + ".xlsx";
                }
    
                fs = new FileStream(path + fileName, FileMode.OpenOrCreate);
                workbook = new XSSFWorkbook();
            }
    
            /// <summary>
            /// 添加工作表
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="sheetName">工作表的名称</param>
            /// <param name="titleName">表题名称</param>
            /// <param name="columnNames">表头名称</param>
            /// <param name="list"></param>
            public void AddSheet<T>(string sheetName, string titleName, string[] columnNames, IList<T> list)
            {
                XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet(sheetName);
    
                int rowIndex = 0;
                //如果有表题名称则创建表题
                if (!string.IsNullOrEmpty(titleName))
                {
                    XSSFRow headRow = (XSSFRow)sheet.CreateRow(rowIndex);
                    headRow.Height = 20 * 30;                               //设置表头高
    
                    //合并单元格( CellRangeAddress()该方法的参数次序是:开始行号,结束行号,开始列号,结束列号。 )
                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, columnNames.Length - 1));
                    headRow.CreateCell(0, NPOI.SS.UserModel.CellType.String).SetCellValue(titleName);
                    
                    XSSFCellStyle headStyle = (XSSFCellStyle)workbook.CreateCellStyle();            //设置样式
                    XSSFFont font = (XSSFFont)workbook.CreateFont();                                //字体
                    font.FontHeightInPoints = 20;
                    font.Boldweight = 700;
                    headStyle.SetFont(font);
                    headRow.GetCell(0).CellStyle = headStyle;
    
                    headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;             //水平对齐
                    headStyle.VerticalAlignment = VerticalAlignment.Center;                         //垂直对齐
    
                    rowIndex++;
                }
    
                //如果有表头则创建表头
                if (columnNames != null)
                {
                    XSSFRow topRow = (XSSFRow)sheet.CreateRow(rowIndex);
                    XSSFCellStyle topStyle = (XSSFCellStyle)workbook.CreateCellStyle();
                    XSSFFont topfont = (XSSFFont)workbook.CreateFont();
                    topfont.FontHeightInPoints = 10;
                    topfont.Boldweight = 700;
                    topStyle.SetFont(topfont);
                    int tag = 0;
                    foreach (string column in columnNames)
                    {
                        topRow.CreateCell(tag).SetCellValue(column);
                        topRow.GetCell(tag).CellStyle = topStyle;
    
                        //设置列宽
                        sheet.SetColumnWidth(tag, (column.Length * 256 * 4));
                        tag++;
                    }
    
                    rowIndex++;
                }
    
                CreateContent(sheet, list, rowIndex);
                //workbook.Add(sheet);
            }
    
            /// <summary>
            /// 输出文件
            /// </summary>
            public void Output()
            {
                workbook.Write(fs);
            }
    
            /// <summary>
            /// 添加表内容
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="sheet"></param>
            /// <param name="list"></param>
            /// <param name="nowRow"></param>
            private void CreateContent<T>(XSSFSheet sheet, IList<T> list, int nowRow)
            {
                T t = (T)Activator.CreateInstance(typeof(T));
                PropertyInfo[] propertity = t.GetType().GetProperties();//取得Model类的所有公有属性
    
                //4 填充内容
                int rowCount = list.Count;
                for (int i = 0; i < rowCount; i++)//循环每一条内容
                {
                    int rowIndex = i + nowRow;
                    XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);//创建一行
    
                    int cellCount = propertity.Length;
                    for (int j = 0; j < cellCount; j++)//循环列
                    {
    
                        PropertyInfo pro = propertity[j];//获取第j个属性
                        object objcellvalue = pro.GetValue(list[i], null);//获取第j个属性的值
                        if (objcellvalue == DBNull.Value || objcellvalue == null)
                        {
                            objcellvalue = DBNull.Value;
                        }
                        XSSFCell newCell = (XSSFCell)dataRow.CreateCell(j);//创建一个单元格
    
                        string cellValue = objcellvalue == DBNull.Value || objcellvalue == null ? "" : objcellvalue.ToString();
    
                        #region 转换
                        switch (objcellvalue.GetType().ToString())
                        {
                            case "System.DateTime"://日期类型
                                newCell.CellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("m/d/yy h:mm");//格式化显示
                                DateTime dateV;
                                if (!DateTime.TryParse(cellValue, out dateV))
                                {
                                    newCell.SetCellValue("");
                                }
                                else
                                {
    
                                    newCell.SetCellValue(dateV);
                                }
    
                                break;
                            case "System.Boolean"://布尔型
                                newCell.SetCellValue(cellValue == "" ? "False" : cellValue);
                                break;
                            default:
                                newCell.SetCellValue(cellValue);
                                break;
    
                        }
                        #endregion
                    }
                }
    
            }
        }

    调用:

                var head = new string[] { "账号", "账号名称", "锁定客户数量", "账号状态", "最后登录时间" };
                Excel excel = new Excel("D:\download", "测试");
                excel.AddSheet("表1", "表1表题", head, result);
    var head_data = new string[] { "URMID", "企业名称", "服务到期时间", "合作金额", "最后登录时间", "在期职位数" }; excel.AddSheet("表2", $"{d.smanName}锁定的客户", head_data, d.cusls); excel.Output();
  • 相关阅读:
    POJ 3114 Tarjan+Dijkstra
    278. First Bad Version
    209. Minimum Size Subarray Sum
    154. Find Minimum in Rotated Sorted Array II
    153. Find Minimum in Rotated Sorted Array
    710. Random Pick with Blacklist
    767. Reorganize String
    524. Longest Word in Dictionary through Deleting
    349. Intersection of Two Arrays
    350. Intersection of Two Arrays II
  • 原文地址:https://www.cnblogs.com/zhangchaoran/p/13803427.html
Copyright © 2011-2022 走看看