在winform项目中,如果要绘制如下的报表:
这种报表简单,实用,可以自己写代码轻松实现,不必去引入第三方dll,从而导致项目不安全.
首先建一个实体类:
/// <summary>
/// 产品表
/// </summary>
[Serializable]
public class Item
{
/// <summary>
/// 产品名称
/// </summary>
public string name { get; set; }
/// <summary>
/// 数量
/// </summary>
public double count { get; set; }
}
从数据库查出相应的数据,并转化成List<Item>集合
调用方法,画图:
public void Draw(List<Item> list)
{
int width = this.zpic.Width;
int height = this.zpic.Height;
Bitmap bit = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bit);
g.Clear(Color.White);
//根据高度,画横条线
int showline = 10;
for (int i = 0; i < showline; i++)
{
g.DrawLine(new Pen(new SolidBrush(Color.Green), 1.0f), 50, height - 20 - i * (height / showline), width - 40, height - 20 - i * (height / showline));
g.DrawString(Convert.ToString(i * 100), new Font("Times New Roman", 10, FontStyle.Regular), new SolidBrush(Color.Black), 20, height - 27 - i * (height / showline));
}
//画一条坐标线
g.DrawLine(new Pen(new SolidBrush(Color.Green), 1.0f), 50, height - 20, 50, 20);
for (int j = 0; j < list.Count; j++)
{
int x, y, w, h;
//间隙大小
int lit = 60;
g.DrawString(list[j].name, new Font("宋体", 10, FontStyle.Regular), new SolidBrush(Color.Black), 76 + lit * j, height - 16);
x = 78 + lit * j;
y = height - 20 - Convert.ToInt32((Convert.ToDouble(list[j].count * (height / showline) / 100)));
//坐标宽度
w = 40;
h = Convert.ToInt32(list[j].count * (height / showline) / 100);
if (list[j].count > 600) { g.FillRectangle(new SolidBrush(Color.FromArgb(56, 129, 78)), x, y, w, h); }
else { g.FillRectangle(new SolidBrush(Color.Red), x, y, w, h); }
}
this.zpic.BackgroundImage = bit;
}
根据自己的项目情况,修改部分参数,即可轻松完成该报表.