关于chart.js插件后台方法
最近做图表统计,发现chart.js插件十分好用,至于怎么好用,用了才知道。
chart插件是利用html5的canvas画布,直接画出图形,不需要用css样式,直接按照要求导入json,直接可以完成绘制。
附上Chart中文文档 http://www.bootcss.com/p/chart.js/docs/

这是chart所需的数据格式,因此为了方便操作,我用c#封装了方法,如下:
public string chart(DataTable dt,string[] fillColor,string[] strokeColor,string[] pointColor, string[] pointStrokeColor)//参数:传入一张表,填充的颜色,选择时的颜色,点的颜色,选择时点的颜色,都是数组格式,有多少列(条形数据多少列)就插入集中颜色
{
string data = "";
if (dt.Columns[0].ColumnName.ToUpper() != "ID")
{
string frist = "";
foreach (DataRow dr in dt.Rows)
{
frist += "'" + dr[0] + "',";
}
frist = frist.Substring(0, frist.Length - 1);
string columns = "";
if (fillColor.Length == strokeColor.Length && fillColor.Length == pointColor.Length && fillColor.Length == pointStrokeColor.Length && fillColor.Length == dt.Columns.Count-1)
{
for (int j = 1; j < dt.Columns.Count; j++)
{
//int i = 0;
string str = "";
foreach (DataRow dr in dt.Rows)
{
str += dr[dt.Columns[j].ColumnName] + ",";
}
str = str.Substring(0, str.Length - 1);
columns += "{label: '" + dt.Columns[j].ColumnName + "',fillColor: '" + fillColor[j-1] + "',strokeColor: '" + strokeColor[j-1] + "',pointColor: '" + pointColor[j-1] + "', pointStrokeColor: '" + pointStrokeColor[j-1] + "',data: [" + str + "]},";
// ++i;
}
}
else
{
throw new Exception("输入颜色数组不正确");
}
columns = columns.Substring(0, columns.Length - 1);
data = "{labels: [" + frist + "],datasets: [" + columns + "]}";
return data;
}
else
{
string frist = "";
foreach (DataRow dr in dt.Rows)
{
frist += "'" + dr[1] + "',";
}
frist = frist.Substring(0, frist.Length - 1);
string columns = "";
if (fillColor.Length == strokeColor.Length && fillColor.Length == pointColor.Length && fillColor.Length == pointStrokeColor.Length && fillColor.Length == dt.Columns.Count-2)
{
for (int j = 2; j < dt.Columns.Count; j++)
{
//int i = 0;
string str = "";
foreach (DataRow dr in dt.Rows)
{
str += dr[dt.Columns[j].ColumnName] + ",";
}
str = str.Substring(0, str.Length - 1);
columns += "{label: '" + dt.Columns[j].ColumnName + "',fillColor: '" + fillColor[j-2] + "',strokeColor: '" + strokeColor[j-2] + "',pointColor: '" + pointColor[j-2] + "', pointStrokeColor: '" + pointStrokeColor[j-2] + "',data: [" + str + "]},";
//++i;
}
}
else
{
throw new Exception("输入颜色数组不正确");
}
columns = columns.Substring(0, columns.Length - 1);
data = "{labels: [" + frist + "],datasets: [" + columns + "]}";
return data;
}
}
直接调用,前台转化为json就行了,

大功告成。

浙公网安备 33010602011771号