实际的工作中,需要输出报表,然而网上很少有通过Aspose.cells创建图表的样例,官网也几乎找不到例子,所以自己折腾了一下,写出了如下代码。
代码语言:javascript复制DataSet dataSet2 = new DataSet("MyDataSet");
// 创建一个 DataTable 并命名为 Table1
DataTable table2 = new DataTable("Table1");
// 添加列到 DataTable
table2.Columns.Add("RowNum", typeof(int));
table2.Columns.Add("CoFullName", typeof(string));
table2.Columns.Add("IE_FLAG", typeof(string));
table2.Columns.Add("CODE_TS", typeof(string));
table2.Columns.Add("G_NAME", typeof(string));
table2.Columns.Add("USD_TOTAL", typeof(double));
table2.Columns.Add("Ratio", typeof(double));
table2.Columns.Add("Months", typeof(string));
DataRow row2 = table2.NewRow();
row2["RowNum"] = 1;
row2["CoFullName"] = "深圳市XX物流有限公司";
row2["IE_FLAG"] = "进口";
row2["CODE_TS"] = "8544200000";
row2["G_NAME"] = "同轴电缆";
row2["Months"] = "2024-01~2024-07";
row2["USD_TOTAL"] = 386786;
row2["Ratio"] = 80.40;
table2.Rows.Add(row2);
DataRow row3 = table2.NewRow();
row3["RowNum"] = 2;
row3["CoFullName"] = "深圳市XX物流有限公司";
row3["CODE_TS"] = "8504101000";
row3["IE_FLAG"] = "进口";
row3["G_NAME"] = "电子镇流器";
row3["Months"] = "2024-01~2024-07";
row3["USD_TOTAL"] = 51599;
row3["Ratio"] = 10.73;
table2.Rows.Add(row3);
DataRow row4 = table2.NewRow();
row4["RowNum"] = 3;
row4["CoFullName"] = "深圳市XX物流有限公司";
row4["CODE_TS"] = "8532241000";
row4["IE_FLAG"] = "进口";
row4["Months"] = "2024-01~2024-07";
row4["G_NAME"] = "陶瓷电容";
row4["USD_TOTAL"] = 42720;
row4["Ratio"] = 8.88;
table2.Rows.Add(row4);
DataRow row5 = table2.NewRow();
row5["RowNum"] = 3;
row5["CoFullName"] = "深圳市XX物流有限公司";
row5["CODE_TS"] = "6404199000";
row5["IE_FLAG"] = "进口";
row5["Months"] = "2024-01~2024-07";
row5["G_NAME"] = "女靴";
row5["USD_TOTAL"] = 12720;
row5["Ratio"] = 8.18;
table2.Rows.Add(row5);
dataSet2.Tables.Add(table2);
//进出口货值TOP10分析模版.xlsx
using (FileStream fs = new FileStream("进出口货值TOP10分析模版.xlsx", FileMode.Open, FileAccess.Read))
{
var workbookx1 = new Aspose.Cells.Workbook(fs);
ExcelReportHelper.ExcelDataFillsV2(dataSet2, workbookx1, true, 1);
Worksheet sheet = workbookx1.Worksheets[0];
// 创建一个图表对象
int chartIndex = sheet.Charts.Add(ChartType.Column, 5, 8, 30, 20);
Chart chart = sheet.Charts[chartIndex];
// 设置图表锚点位置
// 创建一个锚点,定义图表的起始和结束位置
chart.ChartObject.Placement = PlacementType.FreeFloating;
chart.ChartObject.UpperLeftRow = 5;
chart.ChartObject.UpperLeftColumn = 8;
chart.ChartObject.LowerRightRow = 30;
chart.ChartObject.LowerRightColumn = 20;
// 设置X轴数据范围
int startRow = 2;
int endRow = table2.Rows.Count 2;
// 设置Y轴数据范围
Dictionary<string, string> YDic = new Dictionary<string, string>
{
{ "金额(美元)", $"F{startRow 1}:F{endRow}" }
};
foreach (var yData in YDic)
{
int seriesIndex = chart.NSeries.Add(yData.Value, true);
chart.NSeries[seriesIndex].Name = yData.Key;
chart.NSeries[seriesIndex].XValues = $"E{startRow 1}:E{endRow}";
}
// 设置图表位置
chart.ChartObject.Width = 800;
chart.ChartObject.Height = 400;
workbookx1.Save("进出口货值TOP10分析-aspose.xlsx");
}
最终生成的效果如下:
- C# 技术