using System.Collections.Generic;
using System.Linq;
using DOD = DocumentFormat.OpenXml.Drawing;
using DODC = DocumentFormat.OpenXml.Drawing.Charts;
using DODS = DocumentFormat.OpenXml.Drawing.Spreadsheet;
using DOS = DocumentFormat.OpenXml.Spreadsheet;
using DOX = DocumentFormat.OpenXml;
using pkg = DocumentFormat.OpenXml.Packaging; namespace InsertChartTest
{
class Program
{
const string fileName = @"C:\Users\Administrator\source\repos\OpenXMLStudy\OpenXMLStudy\Sum100.xlsx"; static void Main(string[] args)
{
string worksheetName = "Joe";
string title = "New Chart";
Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("abc", );
data.Add("dsa", );
InsertChartInSpreadsheet(fileName, worksheetName, title, data); } private static void InsertChartInSpreadsheet(string docName, string worksheetName, string title,
Dictionary<string, int> data)
{
using (pkg.SpreadsheetDocument document = pkg.SpreadsheetDocument.Open(docName, true))
{
IEnumerable<DOS.Sheet> sheets = document.WorkbookPart.Workbook.Descendants<DOS.Sheet>(); if (sheets == null || sheets.Count() <= )
return; pkg.WorksheetPart worksheetPart = (pkg.WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id); System.Diagnostics.Debug.WriteLine("SheetID:{0}", sheets.First().Id); // DOS.Worksheet worksheet = worksheetPart.Worksheet;
pkg.DrawingsPart drawingsPart = worksheetPart.AddNewPart<pkg.DrawingsPart>(); worksheetPart.Worksheet.Append(new DOS.Drawing()
{
Id = worksheetPart.GetIdOfPart(drawingsPart)
});
worksheetPart.Worksheet.Save(); pkg.ChartPart chartPart = drawingsPart.AddNewPart<pkg.ChartPart>(); //图表实例
chartPart.ChartSpace = new DODC.ChartSpace(); chartPart.ChartSpace.Append(
new DODC.EditingLanguage()
{
Val = new DOX.StringValue("en-US")
}); //图表最外层
DODC.Chart chart = chartPart.ChartSpace.AppendChild<DODC.Chart>(new DODC.Chart()); //图形区
DODC.PlotArea plotArea = chart.AppendChild<DODC.PlotArea>(new DODC.PlotArea()); //布局
DODC.Layout layout = plotArea.AppendChild<DODC.Layout>(new DODC.Layout()); //柱形图
DODC.BarChart barChart = plotArea
.AppendChild<DODC.BarChart>(
new DODC.BarChart(
new DODC.BarDirection()
{
Val = new DOX.EnumValue<DODC.BarDirectionValues>(DODC.BarDirectionValues.Column)
},
new DODC.BarGrouping()
{
Val = new DOX.EnumValue<DODC.BarGroupingValues>(DODC.BarGroupingValues.Clustered)
})); uint i = ; foreach (string key in data.Keys)
{
//柱形图序列
DODC.BarChartSeries barChartSeries = barChart
.AppendChild<DODC.BarChartSeries>(
new DODC.BarChartSeries(//柱形图序列
new DODC.Index()
{
Val = new DOX.UInt32Value(i)
},
new DODC.Order()
{
Val = new DOX.UInt32Value(i)
},
new DODC.SeriesText( //系列文本
new DODC.NumericValue()
{
Text = key
})
)); //字符串常值
DODC.StringLiteral strLit = barChartSeries
.AppendChild<DODC.CategoryAxisData>(
new DODC.CategoryAxisData())
.AppendChild<DODC.StringLiteral>(
new DODC.StringLiteral()); strLit.Append(new DODC.PointCount()
{
Val = new DOX.UInt32Value(1U)
}); strLit.AppendChild<DODC.StringPoint>(new DODC.StringPoint()
{
Index = new DOX.UInt32Value(0U)
})
.Append(new DODC.NumericValue(key)); //原为title //值常值
DODC.NumberLiteral numLit = barChartSeries
.AppendChild<DODC.Values>(new DODC.Values()
).AppendChild<DODC.NumberLiteral>(new DODC.NumberLiteral()
); numLit.Append(new DODC.FormatCode("General")); numLit.Append(new DODC.PointCount()
{
Val = new DOX.UInt32Value(1U)
}); numLit.AppendChild<DODC.NumericPoint>(new DODC.NumericPoint()
{
Index = new DOX.UInt32Value(0u)
}).Append(new DODC.NumericValue(data[key].ToString())); i++;
} barChart.Append(new DODC.AxisId()
{
Val = new DOX.UInt32Value(48650112u)
}); barChart.Append(new DODC.AxisId()
{
Val = new DOX.UInt32Value(48672768u)
}); //分类坐标值
DODC.CategoryAxis catAx = plotArea.AppendChild<DODC.CategoryAxis>(
new DODC.CategoryAxis(
new DODC.AxisId()
{
Val = new DOX.UInt32Value(48650112u)
},
new DODC.Scaling(new DODC.Orientation()
{
Val = new DOX.EnumValue<DODC.OrientationValues>(DODC.OrientationValues.MinMax)
}),
new DODC.AxisPosition()//坐标值位置
{
Val = new DOX.EnumValue<DODC.AxisPositionValues>(DODC.AxisPositionValues.Bottom)
},
new DODC.TickLabelPosition()//标签位置
{
Val = new DOX.EnumValue<DODC.TickLabelPositionValues>(DODC.TickLabelPositionValues.NextTo)
},
new DODC.CrossingAxis()
{
Val = new DOX.UInt32Value(48672768U)
},
new DODC.Crosses()
{
Val = new DOX.EnumValue<DODC.CrossesValues>(DODC.CrossesValues.AutoZero)
},
new DODC.AutoLabeled()
{
Val = new DOX.BooleanValue(true)
},
new DODC.LabelAlignment()
{
Val = new DOX.EnumValue<DODC.LabelAlignmentValues>(DODC.LabelAlignmentValues.Center)
},
new DODC.LabelOffset()
{
Val = new DOX.UInt16Value((ushort))
}
)); //值坐标值
DODC.ValueAxis valAx = plotArea.AppendChild<DODC.ValueAxis>(
new DODC.ValueAxis(
new DODC.AxisId()
{
Val = new DOX.UInt32Value(48672768u)
},
new DODC.Scaling(
new DODC.Orientation()
{
Val = new DOX.EnumValue<DODC.OrientationValues>(DODC.OrientationValues.MinMax)
}),
new DODC.AxisPosition()
{
Val = new DOX.EnumValue<DODC.AxisPositionValues>(DODC.AxisPositionValues.Left)
},
new DODC.MajorGridlines(),
new DODC.NumberingFormat()
{
FormatCode = new DOX.StringValue("General"),
SourceLinked = new DOX.BooleanValue(true)
},
new DODC.TickLabelPosition()
{
Val = new DOX.EnumValue<DODC.TickLabelPositionValues>(DODC.TickLabelPositionValues.NextTo)
},
new DODC.CrossingAxis()
{
Val = new DOX.UInt32Value(48650112U)
},
new DODC.Crosses()
{
Val = new DOX.EnumValue<DODC.CrossesValues>(DODC.CrossesValues.AutoZero)
},
new DODC.CrossBetween()
{
Val = new DOX.EnumValue<DODC.CrossBetweenValues>(DODC.CrossBetweenValues.Between)
})); //图例
DODC.Legend legend = chart.AppendChild<DODC.Legend>(
new DODC.Legend(
new DODC.LegendPosition()
{
Val = new DOX.EnumValue<DODC.LegendPositionValues>(DODC.LegendPositionValues.Right) //图例位置
})); //图可见
chart.Append(new DODC.PlotVisibleOnly()
{
Val = new DOX.BooleanValue(true)
}); chartPart.ChartSpace.Save(); drawingsPart.WorksheetDrawing = new DODS.WorksheetDrawing(); //图例和图形区域大小
DODS.TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild<DODS.TwoCellAnchor>(new DODS.TwoCellAnchor()); //图形区域大小
twoCellAnchor.Append(new DODS.FromMarker(new DODS.ColumnId(""),
new DODS.ColumnOffset(""),
new DODS.RowId(""),
new DODS.RowOffset(""))); //图例区域大小
twoCellAnchor.Append(new DODS.ToMarker(new DODS.ColumnId(""),
new DODS.ColumnOffset(""),
new DODS.RowId(""),
new DODS.RowOffset(""))); //添加图形和图例到区域中
//图形框架
DODS.GraphicFrame graphicFrame =
twoCellAnchor.AppendChild<DODS.GraphicFrame>(new DODS.GraphicFrame());
graphicFrame.Macro = ""; //图表标题
graphicFrame.Append(
new DODS.NonVisualGraphicFrameProperties(
new DODS.NonVisualDrawingProperties()
{
Id = new DOX.UInt32Value(2u),
Name = "Chart 1"
},
new DODS.NonVisualGraphicFrameDrawingProperties()
)); //区域坐标
graphicFrame.Append(
new DODS.Transform(
new DOD.Offset()
{
X = 0L,
Y = 0L
},
new DOD.Extents()
{
Cx = 0L,
Cy = 0L
}
)); //把图形添加到区域中
graphicFrame.Append(
new DOD.Graphic(
new DOD.GraphicData(
new DODC.ChartReference()
{
Id = drawingsPart.GetIdOfPart(chartPart)//指定图形ID
})
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" }
)); twoCellAnchor.Append(new DODS.ClientData()); drawingsPart.WorksheetDrawing.Save(); }
}
}
}

运行上面代码得到图表如图:

注意:上面代码不支持重复运行

利用openxml在Excel中插入图表的更多相关文章

  1. java 在Excel中插入图片 POI实现

    一.POI简介 Jakarta POI 是apache的子项目,目标是处理ole2对象.它提供了一组操纵Windows文档的Java API 目前比较成熟的是HSSF接口,处理MS Excel(97- ...

  2. java POI实现向Excel中插入图片

          做Web开发免不了要与Excel打交道.今天老大给我一个任务-导出Excel.开始想的还是蛮简单的,无非就是查找,构建Excel,response下载即可.但是有一点不同,就是要加入图片, ...

  3. 利用POI获取Excel中图片和图片位置

    利用POI获取Excel中图片和图片位置(支持excel2003or2007多sheet) 转自:http://blog.csdn.net/delongcpp/article/details/8833 ...

  4. 如何使用VSTO自动将Excel中的图表复制到Word

    如何使用VSTO自动将Excel中的图表复制到Word 原文地址:https://code.msdn.microsoft.com/How-to-copy-Chart-in-Excel-a29f9029 ...

  5. 利用Kettle 从Excel中抽取数据写入SQLite

    SQLite作为一种数据库可以配置为Kettle的数据输入和输出,这个例子是从Excel中抽取数据然后写入到SQLite中 配置测试并成功后如下 下面是配置步骤: Excel输入配置 sqlite配置 ...

  6. Java 添加、读取、删除Excel中的图表趋势线

    本文以Java示例介绍如何在Excel中添加趋势线,以及读取趋势线公式.通过文中的方法可支持添加6种不同类型的趋势线,包括Linear.Exponential.Logarithmic.Moving A ...

  7. 使用OpenXml把Excel中的数据导出到DataSet中

    public class OpenXmlHelper { /// <summary> /// 读取Excel数据到DataSet中,默认读取所有Sheet中的数据 /// </sum ...

  8. 利用VBA查找excel中一行某列第一次不为空与最后一列不为空的列数

    昨日同事有需求,想知道每个商品第一次销售的月份,以及最后一次销售的月份. 本想通过什么excel函数来解决,但是找了半天也没找到合适的,最后还是通过VBA来解决吧. 使用方法: Excel工具-宏-V ...

  9. 使用Npoi向Excel中插入图片

    先把数据库中的数据都导入到Excel表格中,把图片地址的路径全部转成绝对路径. 使用Npoi读取刚导出的Excle表格,把图片那个单元格的图片路径读出来,然后用文件流读取图片,然后通过Npoi把图片放 ...

随机推荐

  1. vue项目结构搭建

    1安装node.js,已集成npm 2.临时使用淘宝镜像 npm --registry https://registry.npm.taobao.org install express 3.instal ...

  2. pycharm 配置svn

    1.找到本地svn.exe 2.配置svn路径 3.输入svn路径,然后会进行密码校验 问题 本地的TortoiseSVN在bin目录没有发现svn.exe 原因: 安装TortoiseSVN的时候 ...

  3. FPGA-VHDL课堂学习笔记*01

    FPGA-VHDL课堂学习笔记 记录说明:本文档主要记录大学期间,老师FPGA授课课堂笔记. 代码语言:VHDL 编程软件:MAX+plus II FPGA硬件:FLE-843 03月05日  理论课 ...

  4. cross compile gdbserver

    1. 下载gdb源码,7.12版本,下载地址:ftp://ftp.gnu.org/gnu/gdb.2. 编译gdb:0> cd gdb-7.121> mkdir __install2> ...

  5. 【c】多级指针

    一.一级指针 1.int *p,*p2; p是变量名,*表明是指针,指针指向地址. 在定义时初始化,如int *p_2 = &b; //定义一个指针,指针指向一个地址 先定义再初始化,如int ...

  6. JavaScript获取扫码枪相关资料

    https://blog.csdn.net/jiongxian1/article/details/78906124 https://blog.csdn.net/jifengdalu/article/d ...

  7. 关于js中操作数组的一些方法

    网上找的通篇看了一遍讲的很透收藏了!  转自(https://www.cnblogs.com/blogs-8888/p/6518683.html) 1.锁定数组的长度(让数组的长度变成只读). 1 2 ...

  8. 关于Promise的记录和理解

    在JavaScript中,所有的代码都是单线程执行的,这就导致了其所有的网络请求,IO操作,浏览器时间等都是异步非阻塞的模式执行的,这就使得代码的执行顺序可能会超出我们的掌控. 尤其是当多个异步操作待 ...

  9. java 实现udp通讯

    需求:应用A(通常有多个)和应用B(1个)进行 socket通讯,应用A必须知道应用B的ip地址(在应用A的配置文件中写死的),这个时候就必须把应用B的ip设成固定ip(但是某些时候如更换路由后要重新 ...

  10. Linux下docker报错syntax error:unexpected protocol at end of statement

    ---恢复内容开始--- [Linux]Shell脚本“syntax error: unexpected end of file”原因及处理 :::https://blog.csdn.net/u013 ...