2.4.4 用NPOI操作EXCEL--画Grid

  在NPOI中,本身没有画Grid的方法。但我们知道Grid其实就是由横线和竖线构成的,所在我们可以通过画线的方式来模拟画Grid。

 

HSSFSheet sheet1  =  hssfworkbook.CreateSheet( " Sheet1 " );

HSSFRow row 
=  sheet1.CreateRow( 2 );
row.CreateCell(
1 );
row.HeightInPoints 
=   240 ;
sheet1.SetColumnWidth(
2 9000 );
int  linesCount  =   20 ;

HSSFPatriarch patriarch 
=  sheet1.CreateDrawingPatriarch();
// 因为HSSFClientAnchor中dx只能在0-1023之间,dy只能在0-255之间,所以这里采用比例的方式
double  xRatio  =   1023.0   /  (linesCount * 10 );
double  yRatio  =   255.0   /  (linesCount * 10 );

// 画竖线
int  x1  =   0 ;
int  y1  =   0 ;
int  x2  =   0 ;
int  y2  =   200 ;
for  ( int  i  =   0 ; i  <  linesCount; i ++ )
{
    HSSFClientAnchor a2 
=   new  HSSFClientAnchor();
    a2.SetAnchor((
short ) 2 2 , ( int )(x1  *  xRatio), ( int )(y1  *  yRatio),
            (
short ) 2 2 , ( int )(x2  *  xRatio), ( int )(y2  *  yRatio));
    HSSFSimpleShape shape2 
=  patriarch.CreateSimpleShape(a2);
    shape2.ShapeType 
=  (HSSFSimpleShape.OBJECT_TYPE_LINE);

    x1 
+=   10 ;
    x2 
+=   10 ;
}

// 画横线
x1  =   0 ;
y1 
=   0 ;
x2 
=   200 ;
y2 
=   0 ;
for  ( int  i  =   0 ; i  <  linesCount; i ++ )
{
    HSSFClientAnchor a2 
=   new  HSSFClientAnchor();
    a2.SetAnchor((
short ) 2 2 , ( int )(x1  *  xRatio), ( int )(y1  *  yRatio),
            (
short ) 2 2 , ( int )(x2  *  xRatio), ( int )(y2  *  yRatio));
    HSSFSimpleShape shape2 
=  patriarch.CreateSimpleShape(a2);
    shape2.ShapeType 
=  (HSSFSimpleShape.OBJECT_TYPE_LINE);

    y1 
+=   10 ;
    y2 
+=   10 ;
}

请注意HSSFClientAnchor对象中的dx只能取0-1023之间的数,dy只能取0-255之间的数。我们可以理解为是将单元格的宽和高平分成了1023和255份,设置dx和dy时相当于按比例取对应的座标。最终生成的Excel如下:

2.4.4 用NPOI操作EXCEL--画Grid

 

返回目录

 

你可能感兴趣的:(Excel)