C# 操作Excel 常用整理

目前使用过的

NPOI 来源于Java POI 有一定的受众群体,但里面的注释很少

Spire.XLS 这个当时是为了用转化为PDF功能才体验使用的,推荐程度一般
EPPlus 这个是比较成熟且官方注释也较多,但注释都是英文的,下面将一一举例

NPOI  读写

 

try
            {
                //读模板的方式加载
                string filePath = System.Web.HttpContext.Current.Server.MapPath("~/Template/BasicInfoTemplete.xlsx");
                IWorkbook workbook;
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read);
                workbook = WorkbookFactory.Create(fs);

                ISheet sheet = workbook.GetSheetAt(0);//获取Excel中的第一个Sheet
                ICellStyle cellStyle = workbook.CreateCellStyle();

                //设置单元格上下左右边框线  
                cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                //文字水平和垂直对齐方式  
                cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;

                ICell Cell = null;
                IRow row = null;
                //基础车型列表
                List<UserModel> list = 数据库获取的列表;
                for (int i = 2; i < obj.Count + 2; i++)
                    {
                        row = sheet.CreateRow(i);
                        //第一列的No.
                        Cell = row.CreateCell(0);
                        Cell.CellStyle = cellStyle;
                        Cell.SetCellValue(i - 1);
                        //总共6列
                        for (int j = 1; j <= 5; j++)
                        {
                            Cell = row.CreateCell(j);
                            Cell.CellStyle = cellStyle;
                            Cell.SetCellValue("""""");
                        }
                    }

          //错误案例注释掉,虽然也能达到功能
          /********
var ms = new NpoiMemoryStream(); ms.AllowClose = false; workbook.Write(fs); workbook.Write(ms); ms.Flush(); ms.Position = 0; ms.AllowClose = false; return File(ms, "application/vnd.ms-excel", "基础车型信息参考.xlsx");
    
         **********/
         var ms = new MemoryStream();
        

          workbook.Write(ms);
          //ms.Flush(); 我理解这个是写入文件时候才用到,这里导出应该不需要
          //ms.Seek(0,SeekOrigin.Begin);
          ms.Position = 0;
          return File(ms, "application/vnd.ms-excel", "基础车型信息参考.xlsx");



    } catch (Exception) { throw; } 

//此部分代码为错误代码,之前对Stream不理解导致的一个网上错误案例
//处理 文件流已关闭 public class NpoiMemoryStream : MemoryStream { public NpoiMemoryStream() { AllowClose = true; } public bool AllowClose { get; set; } public override void Close() { if (AllowClose) base.Close(); } }

 

posted @ 2022-03-04 09:08  港城大白鲨  阅读(233)  评论(0编辑  收藏  举报