c#绘制表格

时间:2023-03-09 01:12:27
c#绘制表格

//绘制表格
//定义绘制表格的参数
Pen _Pen = new Pen(Brushes.Black); // VBConversions Note: Initial value cannot be assigned here since it is non-static. Assignment has been moved to the class constructors. //笔
Font _Font = new Font("微软黑体", (float)(10.5F), FontStyle.Bold); //字体样式
int _TWidth = 0;
int _THeight = 0; //表格宽高
int _x = 25; //起始位置
int _Y = 62;
//表格样式数组 、、、、、、、、、、、、注:——Table.getLength(0)=Widths.length
int[,] _Table = new int[,] {{1, 1, 1, 1, 1, 1, 8}, //(0表示不画) (1则表示横线竖线都画) (8表示只画横线不画竖线,9 只画竖线不画横线 )
{1, 1, 1, 1, 1, 1, 0},
{1, 1, 1, 1, 1, 1, 0},
{1, 1, 1, 1, 1, 1, 0},
{1, 1, 1, 1, 1, 1, 0},
{8, 8, 8, 8, 8, 1, 0},
{1, 1, 1, 1, 1, 1, 0},
{8, 8, 8, 8, 8, 1, 8},
{1, 1, 1, 1, 1, 1, 0},
{1, 1, 1, 1, 8, 1, 0},
{1, 8, 8, 8, 8, 1, 0},
{1, 8, 8, 8, 8, 8, 8},
{1, 8, 8, 8, 8, 8, 8},
{1, 8, 8, 8, 8, 8, 8},
{1, 8, 8, 8, 8, 8, 8},
{1, 8, 8, 8, 8, 8, 8}};
int[] _Heights = new int[] { 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 70, 70, 70, 70, 70 }; //行高数组
int[] _Widths = new int[] { 90, 138, 90, 138, 90, 138, 148 }; //列宽数组
private void DrawTable()
{
Bitmap _bmp = new Bitmap(this.Bounds.Width, this.Bounds.Height);
Graphics _G = Graphics.FromImage(_bmp);
_THeight = 0;
_TWidth = 0;
for (int i = 0; i <= _Heights.Length - 1; i++) //计算表格总高
{
_THeight += _Heights[i];
}
for (int i = 0; i <= _Widths.Length - 1; i++) //计算表格总宽
{
_TWidth += _Widths[i];
}
_G.DrawLine(_Pen, _x, _Y, _x, _Y + _THeight); //绘制左边和右边的竖线
_G.DrawLine(_Pen, _x + _TWidth, _Y, _x + _TWidth, _Y + _THeight);
int _TempX = _x;
int _TempY = _Y; //临时存储起始XY坐标
//开始绘制表格内部样式
for (int i = 0; i <= _Table.GetLength(0) - 1; i++) //循环表格样式数组 外循环为行
{
for (int j = 0; j <= _Table.GetLength(1) - 1; j++) //内循环为列
{
if (_Table[i, j] > 0) //0则不进行绘制操作
{
if (_Table[i, j] == 8) //8表示只绘制横线,不绘制竖线
{
_G.DrawLine(_Pen, _TempX, _TempY, _TempX + _Widths[j], _TempY); //绘制横线
_TempX += _Widths[j];
}
else if (_Table[i, j] == 9) //9表示只绘制竖线,不会只横线
{
_G.DrawLine(_Pen, _TempX + _Widths[j], _TempY, _TempX + _Widths[j], _TempY + _Heights[i]); //绘制竖线
_TempX += _Widths[j];
}
else if (_Table[i, j] == 1) //1表示只绘制一个横线,一个竖线
{
_G.DrawLine(_Pen, _TempX, _TempY, _TempX + _Widths[j], _TempY); //先绘制横线
_G.DrawLine(_Pen, _TempX + _Widths[j], _TempY, _TempX + _Widths[j], _TempY + _Heights[i]); //再绘制竖线
_TempX += _Widths[j];
}
else //表示绘制N个横线,一个竖线
{

}
}
}
_TempY += _Heights[i]; //绘制完一行高+
_TempX = _x;
}
_G.DrawLine(_Pen, _x, _Y + _THeight, _x + _TWidth, _Y + _THeight); //绘制最后一行横线
_G.Dispose();
P_Container.BackgroundImage = _bmp;
}

当需要向绘制的表格写入内容的时候只需要用drawstring和drawline类似