[英]C# Change Excel Chart Axis Format using EPPLUS
Is there anyway to change the chart X or Y axis to set a custom label formatting? 无论如何,要更改图表的X轴或Y轴以设置自定义标签格式?
For example, in the XAxis my labels are datetime but the formatting is yyyy-mm-dd hh:mm:ss. 例如,在XAxis中,我的标签为日期时间,但格式为yyyy-mm-dd hh:mm:ss。 I would like to change it to just yyyy-mm-dd.
我想将其更改为yyyy-mm-dd。
Was wondering if it is possible in EPPLUS without using interop 想知道是否可以在不使用互操作的情况下在EPPLUS中实现
This is a bit of a pain with charts and EPPlus. 图表和EPPlus有点麻烦。 They have exposed the
chart.XAxis.Format
property to set the format but does not account for the attribute souceLinked
which, when not set to 0 (default) tells excel to just go with the source data format. 他们公开了
chart.XAxis.Format
属性来设置格式,但没有考虑souceLinked
属性,当未将其设置为0(默认值)时,该属性告诉excel只使用源数据格式。 So you have to set it manually with xml: 因此,您必须使用xml手动设置它:
[TestMethod]
public void Chart_Row_Offset_Test()
{
//Throw in some data
var datatable = new DataTable("tblData");
datatable.Columns.AddRange(new[]
{
new DataColumn("Col1", typeof (DateTime)), new DataColumn("Col2", typeof (int)), new DataColumn("Col3", typeof (object))
});
for (var i = 0; i < 10; i++)
{
var row = datatable.NewRow();
row[0] = DateTime.Now.AddDays(i) ;row[1] = i*10;row[2] = Path.GetRandomFileName();
datatable.Rows.Add(row);
}
//Create a test file
var fi = new FileInfo(@"c:\temp\Chart_Row_Offset.xlsx");
if (fi.Exists)
fi.Delete();
using (var pck = new ExcelPackage(fi))
{
var workbook = pck.Workbook;
var worksheet = workbook.Worksheets.Add("Sheet1");
worksheet.Cells.LoadFromDataTable(datatable, true);
//This would be the axis label format if the XML Attribute is not set below
worksheet.Cells["A2:A11"].Style.Numberformat.Format = "m/d/yyyy";
const int EXCELCHARTWIDTH = 375;
const int EXCELCHARTHEIGHT = 350;
const double EXCELDEFAULTROWHEIGHT = 20.0; //Assuming standard screen dpi
var startCell = (ExcelRangeBase)worksheet.Cells["A1"];
for (var i = 0; i < 10; i++)
{
var chart = worksheet.Drawings.AddChart("chart " + i, eChartType.XYScatterLines);
chart.SetSize(EXCELCHARTWIDTH, EXCELCHARTHEIGHT);
chart.SetPosition(startCell.Start.Row, 0, startCell.Start.Column, 0);
chart.XAxis.Format = "yyyy-mm-dd";
var series = chart.Series.Add(worksheet.Cells["B2:B11"], worksheet.Cells["A2:A11"]);
var chartcellheight = (int)Math.Ceiling(EXCELCHARTHEIGHT / EXCELDEFAULTROWHEIGHT);
startCell = startCell.Offset(chartcellheight, 0);
//Get reference to the chart xml for proper namespace
var xdoc = chart.ChartXml;
var nsm = new XmlNamespaceManager(xdoc.NameTable);
nsm.AddNamespace("default", xdoc.DocumentElement.NamespaceURI);
//Add the attribute to not link to the source data format
var att = xdoc.CreateAttribute("sourceLinked");
att.Value = "0";
var numFmtNode = xdoc.SelectSingleNode("/default:chartSpace/default:chart/default:plotArea/default:valAx/default:numFmt", nsm);
numFmtNode.Attributes.Append(att);
}
pck.Save();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.