C#_NPOI读写Excel

  • 首先效果图:
    C#_NPOI读写Excel_第1张图片
  • 接着上通用代码:
        /// 
        /// 读取Excel
        /// 
        /// 读取文件路径
        /// 
        public IWorkbook Excel_OpenRead(string excelpath)
        {
            IWorkbook workbook = null;
            bool isCompatible = excelpath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);
            FileStream fsRead = File.OpenRead(excelpath);
            if (isCompatible) { workbook = new HSSFWorkbook(fsRead); } else { workbook = new XSSFWorkbook(fsRead); }
            fsRead.Close();
            return workbook;
        }
        
         /// 
         /// 写出Excel
         /// 
         /// 写出文件路径
         /// 写出工作簿
        public void Excel_Write(string excelpath, IWorkbook workbook)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(excelpath));
            FileStream fsWrite = File.Open(excelpath, FileMode.Create, FileAccess.Write);
            workbook.Write(fsWrite);
            fsWrite.Close();
        }

        /// 
        /// Excel单元格样式
        /// 
        /// 工作簿
        /// 水平对齐
        /// 
        public ICellStyle Excel_Style(IWorkbook workbook, string alignment = "居中")
        {
            ICellStyle style = workbook.CreateCellStyle();
            style.BorderTop = BorderStyle.Thin;//上
            style.BorderBottom = BorderStyle.Thin;//下
            style.BorderLeft = BorderStyle.Thin;//左
            style.BorderRight = BorderStyle.Thin;//右
            style.VerticalAlignment = VerticalAlignment.Center;//垂直居中
            style.WrapText = true;//自动换行
            switch (alignment)
            {
                case "居中":
                    style.Alignment = HorizontalAlignment.Center;
                    break;
                case "左":
                    style.Alignment = HorizontalAlignment.Left;
                    break;
                case "右":
                    style.Alignment = HorizontalAlignment.Right;
                    break;
            }
            return style;
        }
        
        /// 
        /// Excel字体样式
        /// 
        /// 工作簿
        /// 字体名称
        /// 字体大小
        /// 字体颜色
        /// 字体加粗
        /// 
        public IFont Excel_Font(IWorkbook workbook, string name = "宋体", int height = 11, string clor = "黑", bool bold = false)
        {
            IFont Font = workbook.CreateFont();// 创建字体
            Font.FontName = name; //跟Excel中的字体值一样,直接写对应的名称即可
            Font.FontHeightInPoints = height; // 字体大小,直接对应Excel中的字体大小
            Font.IsBold = bold;//加粗
            switch (clor)
            {
                case "黑":
                    Font.Color = IndexedColors.Black.Index; // 选择字体颜色
                    break;
                case "红":
                    Font.Color = IndexedColors.Red.Index; // 选择字体颜色
                    break;
            }
            return Font;
        }
  • NPOI:文件,读/写;操作,字体/单元格 直接上个栗子:
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using BorderStyle = NPOI.SS.UserModel.BorderStyle;
using HorizontalAlignment = NPOI.SS.UserModel.HorizontalAlignment;

       private void button1_Click(object sender, EventArgs e)
        {
                string filepath = @"D:\test.xls";
                IWorkbook workbook = Excel_OpenRead(filepath);//获取工作簿
                ISheet sheet = workbook.GetSheetAt(0);//获取第一个工作表
                int iRowCount = sheet.LastRowNum;//获取行数
                ICellStyle style = Excel_Style(workbook);//设置单元格样式
                IFont Font = Excel_Font(workbook, "宋体", 16);//设置字体
                for (int iRow = 0; iRow <= iRowCount; iRow++)
                {
                        if (sheet.GetRow(iRow) is null) { sheet.CreateRow(iRow).CreateCell(15).SetCellValue("未获取到此行有效数据。"); continue; }//遇到空行提示
                        //if (sheet.GetRow(iRow) is null) { sheet.CreateRow(iRow) }//遇到空行不提示
                        string str = Convert.ToString(sheet.GetRow(iRow).GetCell(0));//单元格读取。强制转字符串,遇null不报错
                        sheet.GetRow(iRow).CreateCell(1).SetCellValue("单元格赋值");//单元格赋值
                        //单元格样式设置 据说只能逐格设置 没有批量的方法
                        sheet.GetRow(iRow).Height = 30 * 20;//设置行高
                        style.SetFont(Font);//设置字体
                        sheet.GetRow(iRow).GetCell(0).CellStyle = style;//设置单元格样式
                }
                Excel_Write(filepath, workbook);//文件写出。filepath路径一致相当于Excel保存,不一致为另存。
        }
        
  • NPOI:合并的单元格 同样直接上个栗子:

            ICellStyle style1 = Excel_Style(workbook, "左");
            string[] text = new string[] {
                "文本1",
                "文本2",
                "文本3",
                "文本4",
                "文本5",
                "文本6"
            };
            int r = sheet.LastRowNum;
            int[,] re = new int[,] { { 0, 3 }, { 4, 8 }, { 9, 16 } };
            CellRangeAddress region;
            for (int rr = 0; rr < 2; rr++)
            {
                for (int cc = 0; cc < 3; cc++)
                {
                    if (sheet.GetRow(r + rr) is null) sheet.CreateRow(r + rr);
                    sheet.GetRow(r + rr).CreateCell(re[cc, 0]).SetCellValue(text[rr * 3 + cc]);
                    sheet.GetRow(r + rr).GetCell(re[cc, 0]).CellStyle = style1;
                    region = new CellRangeAddress(r + rr, r + rr, re[cc, 0], re[cc, 1]);
                    sheet.AddMergedRegion(region);//合并单元格
                    RegionUtil.SetBorderLeft(1, region, sheet);//左
                    RegionUtil.SetBorderRight(1, region, sheet);//右
                    RegionUtil.SetBorderTop(1, region, sheet);//顶
                    RegionUtil.SetBorderBottom(1, region, sheet);//底
                }
                sheet.GetRow(r + rr).Height = 50 * 20;
            }

  • NPOI:富文本 最后的栗子(效果图见上):

            string cool = "mingzi_al超cool”
            sheet.GetRow(1).GetCell(0).SetCellValue(cool);
            ICell cell = sheet.GetRow(1).GetCell(0);
            IFont Font = Excel_Font(workbook, "宋体", 16, "红");
            IRichTextString richString = null;
            if (sheet.Header.ToString().Contains("XSSF"))
            {
                richString = new XSSFRichTextString(BT);
            }
            else
            {
                richString = new HSSFRichTextString(BT);
            }
            int cool_Strat = cool.ToString().IndexOf("cool");
            int cool_End = cool_Strat  + cool .Length;
            richString.ApplyFont(cool_Strat , cool_End , Font);
            cell.SetCellValue(richString);
            

你可能感兴趣的:(C#,c#)