C# EPPlus创建excel、读写excel,设置表格样式

首先在NuGet下载EPPlus包

在这里插入图片描述

创建Excel并写入内容

  /// <summary>
        /// 创建Excel
        /// </summary>
        public void CrateExcel()
        {
            //文件保存路径
            string path = "F:/text.xlsx";
            FileInfo fileInfo = new FileInfo(path);
            using (ExcelPackage package = new ExcelPackage(fileInfo))
            {
                //创建sheet1
                ExcelWorksheet sheet = package.Workbook.Worksheets.Add("sheet1");
                //设置基本样式
                sheet.Cells.Style.Font.Name = "宋体";
                sheet.Cells.Style.Font.Size = 11F;
                sheet.Cells.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                //设置指定单元格内容
                sheet.Cells[1, 1].Value = "降板高度";
                sheet.Cells[1, 2].Value = "生成填充区域";
                sheet.Cells[1, 3].Value = "颜色R";
                sheet.Cells[1, 4].Value = "颜色G";
                sheet.Cells[1, 5].Value = "颜色B";
                sheet.Cells[1, 6].Value = "RGB值";
                sheet.Cells[1, 7].Value = "填充样式";
                //设置行高
                sheet.Row(1).Height = 19.5;
                //设置区域背景颜色(设置背景颜色之前一定要设置PatternType)
                sheet.Cells["A1:G1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
                sheet.Cells["A1:G1"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(232, 232, 232));

                for (int i = 1; i <= 7; i++)
                {
                    //设置单元格区域的边框
                    sheet.Cells[1, i].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin, System.Drawing.Color.Black);
                }
                //保存
                package.Save();
            }
        }

EPPlus读取excel内容

 /// <summary>
        /// 读取Excel表格内容
        /// </summary>
        public void ReadExcel()
        {
            //文件路径
            string path = "F:/text.xlsx";
            FileStream fs = new FileStream(path, FileMode.Open);
            using (ExcelPackage package = new ExcelPackage(fs))
            {
                ExcelWorksheet sheet = package.Workbook.Worksheets[1];
                int n = sheet.Dimension.End.Row;
                for (int i = 2; i <= n; i++)
                {
                    var test = sheet.GetValue(i, 1).ToString();
                }
            }
        }
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值