Create workbook It's plain to create an Excel file, and of course the more accurate representation in Npoi is to create a workbook object stream in memory.
This section, as the opening chapter of Chapter 2nd, will be explained in more detail to help Npoi learners better understand the composition and use of Npoi.
Npoi. HSSF is a namespace specifically responsible for the Excel Biff format, where developers use objects primarily in NPOI.HSSF.UserModel and Npoi. HSSF. Under the Util namespace, the workbook that we're going to talk about here is the NPOI.HSSF.UserModel.HSSFWorkbook class, which is responsible for creating the. xls document, It implements the NPOI.SS.UserModel.IWorkbook interface.
Before we start creating workbook, we need to reference some of the necessary Npoi assembly in the project, and the new Npoi is simplified to 2 DLLs, as shown below
NPOI.dll
Ionic.Zip.dll
To create a new XLS file is really simple, as long as we initialize a new Hssfworkbook instance, as follows:
| 123 |
usingNPOI.HSSF.UserModel;...HSSFWorkbook hssfworkbook =newHSSFWorkbook(); |
Of course you can also use the new SS interface directly, as shown below:
| 1234 |
usingNPOI.SS.UserModel;using NPOI.HSSF.UserModel;...IWorkbook hssfworkbook =newHSSFWorkbook(); |
The result of the creation of these two methods is exactly the same as the Hssfworkbook.
Creating some restrictions so that the created workbook open in Excel will be an error, because Excel specifies that a workbook must have at least 1 sheet, which is why in the Excel interface, Create a new workbook by default, a new 3 sheet will be created. Therefore, you must add the following code to create sheet to ensure that the resulting file is normal:
| 1 |
ISheet sheet = hssfworkbook.CreateSheet("new sheet"); |
If you want to create a standard Excel file that has 3 sheet, you can use the following code:
| 123 |
hssfworkbook.CreateSheet("Sheet1");hssfworkbook.CreateSheet("Sheet2");hssfworkbook.CreateSheet("Sheet3"); |
Finally, the Hssfworkbook instance is written to the file as follows:
| 123 |
FileStream file = newFileStream(@"test.xls", FileMode.Create);hssfworkbook.Write(file);file.Close(); |
C # Create Excel