C# 操作Excel加水印

首先下载免费版的Excel组件- Spire.XLS,安装完成后在bin目录里面有需要用到的dll文件,引用到自己项目里面。

 我这里全引进来了,一共就四个:

C# 操作Excel加水印_第1张图片

界面

C# 操作Excel加水印_第2张图片

效果

C# 操作Excel加水印_第3张图片

 

全部代码

  private static 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;
        }

        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");
        }

 

转载于:https://www.cnblogs.com/bin521/p/9875795.html

你可能感兴趣的:(C# 操作Excel加水印)