C# 如何给Excel添加水印

大数据时代,数据对企业和个人而言都显得尤为重要。Excel作为一种编辑处理数据的常用工具同样广泛地应用于商业或者政务等各个场合和办公环境。想要声明一些重要的工作表格数据或进行保护时,我们可以通过一定方法来进行保护,可以进行文档加密或者添加水印的方式。我们知道在Word中可以添加文本或者是图片水印,但是在Excel中,我们没法直接添加水印。那该怎么办呢?虽然我们没法直接在Excel文件中直接添加,但是在C#中,我们可以通过代码形式来实现。这里,我发现了一个不错的方法来添加Excel水印,用到了组Spire.XLS for. NET。文章转载自 http://www.cnblogs.com/Yesi/p/5915251.html

下面是全部的代码:

using System;
using System.Drawing;
using System.Windows.Forms;
using Spire.Xls;
 
namespace Add_Watermark_To_Excel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            //初始化一个新工作簿并加载要添加水印的文件
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.xlsx");
            //在页眉插入图片
            Font font = new System.Drawing.Font("arial", 40);
            String watermark = "内部资料";
            foreach (Worksheet sheet in workbook.Worksheets)
            {
                //调用DrawText()方法新建图片
                System.Drawing.Image imgWtrmrk = DrawText(watermark, font, System.Drawing.Color.LightCoral, System.Drawing.Color.White, sheet.PageSetup.PageHeight, sheet.PageSetup.PageWidth);
                //将页眉图片设置为左对齐
                sheet.PageSetup.LeftHeaderImage = imgWtrmrk;
                sheet.PageSetup.LeftHeader = "&G";
                //水印只会在此种模式下显现
                sheet.ViewMode = ViewMode.Layout;
            }
            workbook.SaveToFile("水印.xlsx", ExcelVersion.Version2010);
            System.Diagnostics.Process.Start("水印.xlsx");
        }
       <br>       private static System.Drawing.Image DrawText(String text, System.Drawing.Font font, Color textColor, Color backColor, double height, double width)
        {
            //创建一个指定宽度和高度的位图图像
            Image img = new Bitmap((int)width, (int)height);
            Graphics drawing = Graphics.FromImage(img);
            //获取文本大小
            SizeF textSize = drawing.MeasureString(text, font);
            //旋转图片
            drawing.TranslateTransform(((int)width - textSize.Width) / 2, ((int)height - textSize.Height) / 2);
            drawing.RotateTransform(-45);
            drawing.TranslateTransform(-((int)width - textSize.Width) / 2, -((int)height - textSize.Height) / 2);
            //绘制背景
            drawing.Clear(backColor);
            //创建文本刷
            Brush textBrush = new SolidBrush(textColor);
            drawing.DrawString(text, font, textBrush, ((int)width - textSize.Width) / 2, ((int)height - textSize.Height) / 2);
            drawing.Save();
            return img;
        }
    }  
}

 对比效果图:

猜你喜欢

转载自miaonly.iteye.com/blog/2399766