Do you still remember the 9-9 multiplication table in elementary school? In this section, we will learn how to use npoi through C #
Code Generate an Excel multiplication table. To generate a 9-9 multiplication table, the cycle must be indispensable, as shown below:
Hssfsheet sheet1 = Hssfworkbook. createsheet ( " Sheet1 " );
Hssfrow row;
Hssfcell cell;
For ( Int Rowindex = 0 ; Rowindex < 9 ; Rowindex ++ )
{
Row = Sheet1.createrow (rowindex );
For ( Int Colindex = 0 ; Colindex <= Rowindex; colindex ++ )
{
Cell = Row. createcell (colindex );
Cell. setcellvalue (string. Format ( " {0} * {1} = {2} " , Rowindex + 1 , Colindex + 1 , (Rowindex + 1 ) * (Colindex + 1 )));
}
}
The code is actually very simple, that is, it calls cell. setcellvalue (STR) cyclically to write nine rows of data, and the number of cells written in each row increases progressively. The Excel Style generated after execution is as follows:
complete code: Code
code highlighting produced by actipro codehighlighter (freeware)
http://www.CodeHighlighter.com/
--> using system;
using system. collections. generic;
using system. LINQ;
using system. text;
using npoi. hssf. usermodel;
using system. io;
using npoi. hpsf;
NamespaceTimestables
{
Public ClassProgram
{
StaticHssfworkbook;
Static VoidMain (String[] ARGs)
{
Initializeworkbook ();
Hssfsheet sheet1 = Hssfworkbook. createsheet ( " Sheet1 " );
Hssfrow row;
Hssfcell cell;
For ( Int Rowindex = 0 ; Rowindex < 9 ; Rowindex ++ )
{
Row = Sheet1.createrow (rowindex );
For ( Int Colindex = 0 ; Colindex <= Rowindex; colindex ++ )
{
Cell = Row. createcell (colindex );
Cell. setcellvalue (string. Format ( " {0} * {1} = {2} " , Rowindex + 1 , Colindex + 1 , (Rowindex + 1 ) * (Colindex + 1 )));
}
}
Writetofile ();
}
Static Void Writetofile ()
{
// Write the stream data of workbook to the root directory
Filestream File = New Filestream ( @" Test.xls " , Filemode. Create );
Hssfworkbook. Write (File );
File. Close ();
}
Static VoidInitializeworkbook ()
{
Hssfworkbook= NewHssfworkbook ();
// Create a entry of documentsummaryinformation
Documentsummaryinformation DSI = Propertysetfactory. createdocumentsummaryinformation ();
DSI. Company = " Npoi team " ;
Hssfworkbook. documentsummaryinformation = DSI;
// Create a entry of summaryinformation
Summaryinformation Si = Propertysetfactory. createsummaryinformation ();
Si. Subject = " Npoi SDK example " ;
Hssfworkbook. summaryinformation = Si;
}
}
}
Returned directory