用Spire.XLS给Excel添加水印,打印水印

我的需求:给已存在的Excel添加水印,打印的时候有水印。并且可以传多组水印,可以设置水印位置,水印颜色,水印文本,水印字符大小,水印位置等等

  1. 效果图
  2. 需要引用Spire.XLS.dll插件,NPOI.dll插件
  3. ExcelController.cs 类
  4. ExcelObj.cs 类
    用Spire.XLS给Excel添加水印,打印水印_第1张图片
    /// 
    /// Excel文件添加水印
    /// 
    public class ExcelController
    {
        public ExcelController() { }
        /// 
        /// Excel文件添加水印
        /// 
        /// Excel文件地址
        /// Excel文件添加水印之后保存的地址
        public void ExcelAddWatermark(string filePath, string saveFilePath)
        {
            ExcelAddWatermark(filePath, saveFilePath, new ExcelObj());
        }
        /// 
        /// Excel文件添加水印
        /// 
        /// Excel文件地址
        /// Excel文件添加水印之后保存的地址
        /// Excel对象
        public void ExcelAddWatermark(string filePath, string saveFilePath, ExcelObj excelObj)
        {
            List<ExcelObj> excelObjs = new List<ExcelObj>();
            excelObjs.Add(excelObj);
            ExcelAddWatermark(filePath, saveFilePath, excelObjs);
        }
        /// 
        /// Excel文件添加水印
        /// 
        /// Excel文件地址
        /// Excel文件添加水印之后保存的地址
        /// Excel对象
        public void ExcelAddWatermark(string filePath, string saveFilePath, List<ExcelObj> excelObjs)
        {
            //创建一个Workbook类对象并加载Excel文档
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(filePath);
            string tempDelSheetPath = null;
            try
            {
                ExcelObj excelObj = excelObjs.First();
                //在页眉中插入图片作为模拟水印
                //遍历工作簿中所有工作表
                foreach (Worksheet sheet in workbook.Worksheets)
                {
                    if (excelObj.Height == 0 || excelObj.Width == 0)
                    {
                        excelObj.Width = (int)sheet.PageSetup.PageWidth;
                        excelObj.Height = (int)sheet.PageSetup.PageHeight;
                    }
                    //调用DrawText()方法创建的图片
                    Image imgWtrmrk = GetImage(filePath, excelObjs);
                    //插入图片作为LeftHeaderImage
                    sheet.PageSetup.LeftHeaderImage = imgWtrmrk;
                    sheet.PageSetup.LeftHeader = "&G";
                    //设置视图模式,此方法中页眉水印仅在Layout模式下直观可见
                    sheet.ViewMode = ViewMode.Layout;
                }
                //保存文档
                workbook.SaveToFile("ExcelAddWatermarkDemo.xlsx");
                File.Copy(workbook.FileName, saveFilePath, true);
                workbook.Dispose();

                tempDelSheetPath = DelSheet(saveFilePath);
                File.Copy(tempDelSheetPath, saveFilePath, true);
                //是否预览文档
                if (excelObj.Preview)
                { 
                    System.Diagnostics.Process.Start(saveFilePath);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                string tempPath = Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + "_tempPath.png";
                File.Delete(Path.GetDirectoryName(tempPath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + "_temp.png");
                File.Delete(tempPath);
                File.Delete(tempDelSheetPath);
            }
        }

        /// 
        /// 获取水印文本
        /// 
        /// ExcelObj对象
        /// 
        private string GetTexts(ExcelObj excelObj)
        {
            string text = "";
            for (int i = 0; i < excelObj.TextCounts; i++)
            {
                text = excelObj.Text + "    " + text;
            }
            return text;
        }
        /// 
        /// 获取水印图片模板
        /// 
        /// 文件路径
        /// ExcelObj对象
        /// 图片路径
        private string GetImagePath(string filePath, ExcelObj excelObj)
        {
            Image tempImage = new Bitmap(excelObj.Width, excelObj.Height);
            Graphics drawing = Graphics.FromImage(tempImage);
            drawing.Clear(Color.White);
            drawing.Save();
            string tempPath = Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + "_tempPath.png";
            tempImage.Save(tempPath);
            return tempPath;
        }
        /// 
        /// 根据图片模板获取水印图片
        /// 
        /// 文件地址
        /// ExcelObj对象集合
        /// 
        private Image GetImage(string filePath, List<ExcelObj> excelObjs)
        {
            string tempPath = null;
            string path = null;
            Bitmap bitmap = null;
            tempPath = GetImagePath(filePath, excelObjs.First());
            try
            {
                foreach (ExcelObj excelObj in excelObjs)
                {
                    using (Image image = Image.FromFile(tempPath))
                    {
                        bitmap = new Bitmap(image);
                        //图片的宽度与高度                   
                        int width = bitmap.Width, height = bitmap.Height;
                        string text = GetTexts(excelObj);
                        Graphics g = Graphics.FromImage(bitmap);
                        Font crFont = new Font(excelObj.FoneType, excelObj.FontSize);
                        SizeF crSize = new SizeF();
                        crSize = g.MeasureString(text, crFont);
                        SolidBrush semiTransBrush;
                        semiTransBrush = new SolidBrush(excelObj.TextColor);
                        switch (excelObj.WatermarkPosition)
                        {
                            case ExcelObj.WatermarkPositions.LeftTop://左上角
                                g.TranslateTransform(0, 123);
                                g.RotateTransform(-45);
                                for (int i = 0; i < excelObj.Rows; i++)
                                {
                                    g.DrawString(text, crFont, semiTransBrush, new PointF(-i * 100, i * 100));
                                }
                                break;
                            case ExcelObj.WatermarkPositions.LeftCenter://左中间
                                g.TranslateTransform(0, height / 2);
                                g.RotateTransform(-45);
                                for (int i = 0; i < excelObj.Rows; i++)
                                {
                                    g.DrawString(text, crFont, semiTransBrush, new PointF(-i * 100, i * 100));
                                }
                                break;
                            case ExcelObj.WatermarkPositions.LeftDown://左下角
                                g.TranslateTransform(0, height);
                                g.RotateTransform(-45);
                                for (int j = 0; j < excelObj.Rows; j++)
                                {
                                    g.DrawString(text, crFont, semiTransBrush, 0 + j * 100, -20 + j * 100);
                                }
                                break;
                            case ExcelObj.WatermarkPositions.Center://中间
                                crSize = g.MeasureString(excelObj.Text, crFont);
                                g.TranslateTransform((width / 2 - (float)(crSize.Width / 2 / 1.4)), (height / 2 + (float)(crSize.Width / 2 / 1.4)));
                                g.RotateTransform(-45);
                                for (int i = 0; i < excelObj.Rows; i++)
                                {
                                    g.DrawString(excelObj.Text, crFont, semiTransBrush, 0 + i * 100, 0 + i * 100);
                                }
                                break;
                            case ExcelObj.WatermarkPositions.RightDown://右下角
                                g.TranslateTransform(width / 2, height);
                                g.RotateTransform(-45);
                                for (int j = 0; j < excelObj.Rows; j++)
                                {
                                    g.DrawString(text, crFont, semiTransBrush, 0 + j * 100, -20 + j * 100);
                                }
                                break;
                            case ExcelObj.WatermarkPositions.Whole://整个页面
                                g.TranslateTransform(0, 123);
                                g.RotateTransform(-45);
                                for (int i = 0; i < 20; i++)
                                {
                                    g.DrawString(text, crFont, semiTransBrush, new PointF(-i * 100, i * 100));
                                }
                                break;
                            case ExcelObj.WatermarkPositions.Normal://
                                g.TranslateTransform(0, height);
                                g.RotateTransform(-45);
                                for (int j = 0; j < 29; j++)
                                {
                                    for (int i = 0; i < 29; i++)
                                    {
                                        g.DrawString(excelObj.Text, crFont, semiTransBrush, new PointF(i * 100 + j * 180, -i * 100 + j * 180));
                                    }
                                }
                                break;
                            default:
                                g.TranslateTransform(0, 123);
                                g.RotateTransform(-45);
                                for (int i = 0; i < 20; i++)
                                {
                                    g.DrawString(text, crFont, semiTransBrush, new PointF(-i * 100, i * 100));
                                }
                                break;
                        }
                        path = Path.GetDirectoryName(tempPath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + "_temp.png";
                        bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                    File.Copy(path, tempPath, true);
                }
                return bitmap;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// 
        /// 删除多余Evaluation Warning页
        /// 
        /// 
        private string DelSheet(string filePath)
        {
            try
            {
                NPOI.SS.UserModel.IWorkbook workbook = null;
                string tempPath = Path.GetDirectoryName(filePath) + "\\" + "TempDelSheetPath" + Path.GetExtension(filePath);

                FileInfo temp = new FileInfo(tempPath);
                if (temp.Exists)
                {
                    temp.Delete();
                }
                FileStream fs = File.Create(tempPath);
                XSSFWorkbook x1 = new XSSFWorkbook();
                x1.Write(fs);
                fs.Close();
                FileStream fileRead = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                if (Path.GetExtension(filePath) == ".xls")
                {
                    workbook = new HSSFWorkbook(fileRead);
                    for (int x = 0; x < workbook.NumberOfSheets; x++)
                    {
                        if (workbook.GetSheetName(x) == "Evaluation Warning")
                        {
                            workbook.RemoveSheetAt(x);
                        }
                    }
                }
                else
                {
                    workbook = new XSSFWorkbook(fileRead);
                    int sCounts = workbook.NumberOfSheets;
                    for (int x = 0; x < workbook.NumberOfSheets; x++)
                    {
                        if (workbook.GetSheetName(x) == "Evaluation Warning")
                        {
                            workbook.RemoveSheetAt(x);
                        }
                    }
                }
                fileRead.Close();
                using (FileStream fileSave = new FileStream(tempPath, FileMode.Open, FileAccess.Write))
                {
                    workbook.Write(fileSave);
                }
                workbook.Close();
                return tempPath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
    public class ExcelObj
    {
        #region 字段
        private int rows = 1;
        private int width =0;
        private int height =0;
        private int textCounts = 7;
        private float fontSize = 35;
        private bool preview = true;
        private string foneType = "宋体";
        private Color textColor = Color.Red;
        private String text = "机密文件,禁止外泄";
        private WatermarkPositions watermarkPosition = WatermarkPositions.Center;
        #endregion

        #region 属性
        /// 
        /// Excel水印行数
        /// 
        public int Rows { get => rows; set => rows = value; }
        /// 
        /// Excel文件的宽度
        /// 
        public int Width { get => width; set => width = value; }
        /// 
        /// Excel文件的高度
        /// 
        public int Height { get => height; set => height = value; }
        /// 
        /// Excel水印文本:默认值:机密文件,禁止外泄
        /// 
        public string Text { get => text ;  set  =>  text = value; }
        /// 
        /// 是否打开预览Excel文件 默认值:false
        /// 
        public bool Preview { get => preview; set => preview = value; }
        /// 
        /// Excel水印文本的字体大小  默认值:35
        /// 
        public float FontSize { get => fontSize; set => fontSize = value; }
        /// 
        /// Excel水印文本的字体类型 默认值:宋体
        /// 
        public string FoneType { get => foneType; set => foneType = value; }
        /// 
        /// Excel水印文本的字体颜色 默认值:红色
        /// 
        public Color TextColor { get => textColor; set => textColor = value; }
        /// 
        /// Excel水印文本一行循环的个数 默认值:11
        /// 
        public int TextCounts { get => textCounts; set => textCounts = value; }
        /// 
        /// Excel水印文本的显示位置  默认值: 中间
        /// 
        public WatermarkPositions WatermarkPosition { get => watermarkPosition; set => watermarkPosition = value; }
        #endregion
        /// 
        /// 水印位置
        /// 
        public enum WatermarkPositions { LeftTop, LeftCenter, LeftDown, RightDown, Center, Whole, Normal }
    }

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