Spire.XLS 支持最多添加186种现成形状,如三角形,箭头和标注到Excel工作表。 本文演示如何使用Spire.XLS 和C#将形状插入Excel工作表,并使用颜色和图片填充形状。
详细步骤:
Step 1: 实例化一个Workbook对象并获取第一个工作表。
Workbook workbook = new Workbook(); Worksheet sheet = workbook.Worksheets[0];
Step 2: 添加三角形,并填充纯色的形状。
//Add a triangle shape IPrstGeomShape triangle = sheet.PrstGeomShapes.AddPrstGeomShape(2, 2, 100, 100, PrstGeomShapeType.Triangle); //Fill the triangle with solid color triangle.Fill.ForeColor = Color.Yellow; triangle.Fill.FillType = ShapeFillType.SolidColor;
Step 3: 添加心形并用渐变色填充形状。
//Add a heart shape IPrstGeomShape heart = sheet.PrstGeomShapes.AddPrstGeomShape(2, 5, 100, 100, PrstGeomShapeType.Heart); //Fill the heart with gradient color heart.Fill.ForeColor = Color.Red; heart.Fill.FillType = ShapeFillType.Gradient;
Step 4: 使用默认颜色添加箭头形状。
IPrstGeomShape arrow = sheet.PrstGeomShapes.AddPrstGeomShape(10, 2, 100, 100, PrstGeomShapeType.CurvedRightArrow);
Step 5: 添加云形,并用自定义图片填充形状。
//Add a cloud shape IPrstGeomShape cloud = sheet.PrstGeomShapes.AddPrstGeomShape(10, 5, 100, 100, PrstGeomShapeType.Cloud); //Fill the cloud with picture cloud.Fill.CustomPicture(Image.FromFile("Hydrangeas.jpg"), "Hydrangeas.jpg"); cloud.Fill.FillType = ShapeFillType.Picture;
Step 6: 保存文件。
workbook.SaveToFile("AddShapes.xlsx", ExcelVersion.Version2013);
截图:
完整代码:
using System.Drawing; using Spire.Xls; using Spire.Xls.Core; namespace Add_shapes_to_Excel { class Program { static void Main(string[] args) { //Instantiate a workbook object Workbook workbook = new Workbook(); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Add a triangle shape IPrstGeomShape triangle = sheet.PrstGeomShapes.AddPrstGeomShape(2, 2, 100, 100, PrstGeomShapeType.Triangle); //Fill the triangle with solid color triangle.Fill.ForeColor = Color.Yellow; triangle.Fill.FillType = ShapeFillType.SolidColor; //Add a heart shape IPrstGeomShape heart = sheet.PrstGeomShapes.AddPrstGeomShape(2, 5, 100, 100, PrstGeomShapeType.Heart); //Fill the heart with gradient color heart.Fill.ForeColor = Color.Red; heart.Fill.FillType = ShapeFillType.Gradient; //Add an arrow shape with default color IPrstGeomShape arrow = sheet.PrstGeomShapes.AddPrstGeomShape(10, 2, 100, 100, PrstGeomShapeType.CurvedRightArrow); //Add a cloud shape IPrstGeomShape cloud = sheet.PrstGeomShapes.AddPrstGeomShape(10, 5, 100, 100, PrstGeomShapeType.Cloud); //Fill the cloud with custom picture cloud.Fill.CustomPicture(Image.FromFile("Hydrangeas.jpg"), "Hydrangeas.jpg"); cloud.Fill.FillType = ShapeFillType.Picture; //Save the file workbook.SaveToFile("AddShapes.xlsx", ExcelVersion.Version2013); } } }
慧都控件网