NPOI based on Excel for simple operation

1. About NPOI

  NPOI is an open source for reading and writing Excel in C # program, WORD and other project components Microsoft OLE2 documents, using NPOI can read and write to Word or Excel documents without installing Office.

2. Use NPOI benefits

  1. Another way to program in C # using .NET operating Excel is built-in Excel API, but this method requires runtime environment installed Microsoft Excel, use Excel NPOI can operate on devices not installed the Microsoft Office Excel.
  2. Because the server is generally not such a huge installed office software office, so NPOI adapted to generate a data file on the server side.
  3. It supports almost all file formats Office97 ~ Office2007 of.

3. NPOI use

  NPOI management levels which are: workbook-> worksheet-> row-> cell, relational database analogy is this:

NPOI

Explanation

Relational Database

workbook

Excel files

database

worksheet

Worksheet

table

row

Row

record record

cell

Cell

field field

3.1 acquire DLL

   Option 1: quoted by Nuget command-line installation NPOI

Install-Package NPOI -Version 2.4.0

   Option 2: Search directly in the VS Nuget package manager "NPOI" get

3.2 The NPOI the DLL into the project

using NPOI; //基础辅助库
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;

   Which, NPOI use HSSFWorkbook class to handle xls, XSSFWorkbook classes to handle xlsx, they inherit the interface IWorkbook, it is possible to unify with files xls and xlsx format by IWorkbook. (In this paper, for example XLSX)

3.3 to create and write Excel

  (1)   Create an Excel file

Workbook2007 = XSSFWorkbook new new XSSFWorkbook (); // create xlsx workbook 
HSSFWorkbook workbook2003 = new new HSSFWorkbook (); // Create the workbook xls

  Excel Workbook a provision must take at least one Sheet, so after creating the Excel Sheet must be created at the same time to ensure that the generated code files properly.

ISheet sheet = workbook2007.CreateSheet("sheet1"); //创建一个Sheet

       Create rows and columns:

Row = sheet.CreateRow the IRow ( 0 ); // create a row 
ICell Cell row.CreateCell = ( 0 ); // Create a

  After creating XSSFWorkbook instance, to write the file:

FileStreamfile =new FileStream(@"NpoiTest.xlsx", FileMode.Create);
workbook2007.Write(file);
file.Close();
workbook2007.Close();

   After generates Excel files in the specified directory.

  (2) to write data to an Excel file

  Write data to follow a certain order, can be summarized as: read (or create a new workbook) -> Get the worksheet -> add rows to the worksheet -> add a cell for each row -> to a cell assignment.

Workbook2007 = XSSFWorkbook new new XSSFWorkbook (); // create xlsx workbook 
workbook2007.CreateSheet ( " Sheet1 " );   // Create a Sheet worksheet
 // ISheet Sheet = workbook2007.CreateSheet ( "Sheet1"); 
HSSFSheet SheetOne = (HSSFSheet ) workbook2007.GetSheet ( " Sheet1 " ); // Get the name of Sheet1
 // worksheet added first row index starts from 0 
for ( int I = 0 ; I < 2 ; I ++ ) 
{ 
    SheetOne.CreateRow (I); // add to row 2 SheetOne
     //Row = SheetOne.CreateRow the IRow (I); 
}
 // Create three cells of each row 
HSSFRow SheetRow = (HSSFRow) SheetOne.GetRow ( 0 );   // Get Sheet1 worksheet first line 
HSSFCell [] = SheetCell new new HSSFCell [ . 3 ];
 for ( int I = 0 ; I < . 3 ; I ++ ) 
{ 
    SheetCell [I] = (HSSFCell) SheetRow.CreateCell (I);   // create three cell is a first row
     // ICell headcell = SheetRow .CreateCell (I); 
}
 // after the assignment can create 
SheetCell [ 0 ] .SetCellValue ( " the CellValue ");        
SheetCell[1].SetCellValue("CellValue2");
SheetCell[2].SetCellValue("CellValue3");
FileStream file2007 = new FileStream(@"E:\Excel2007.xls", FileMode.Create);
workbook2007.Write(file2007);
file2007.Close();
workbook2007.Close();

//转化为字节数组
//MemoryStream ms = new MemoryStream();
//workbook.Write(ms);
//ms.Flush();
//ms.Position = 0;
//return ms; 

  (3) to read Excel data file

  workbook writing need the help of FileStream to open a file stream, in the creation of FileStream, you can save incoming data path and file name.

  HSSFWorkbook class and XSSFWorkbook classes inherit from IWorkbook class, so I do not know when the Excel file to be read when xls or xlsx, IWorkbook can be used to declare a variable universal workbook, and then passed in the file name or judgment is xls xlsx.

IWorkbook workbook = null;  //新建IWorkbook对象
string fileName = "E:\\Excel2007.xls";
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
{
    workbook = new XSSFWorkbook(fileStream);  //xlsx数据读入workbook
}
else if (fileName.IndexOf(".xls") > 0) // 2003 version 
{ 
    Workbook = new new HSSFWorkbook (fileStream);   // XLS data reading Workbook 
} 
ISheet Sheet = workbook.GetSheetAt ( 0 );   // get the first sheet 
the IRow Row; // = sheet.GetRow (0 ); // new current line data sheet 
for ( int i = 0 ; i <sheet.LastRowNum; i ++)   // for each row of the worksheet 
{ 
    row = sheet.GetRow (i);    // row i-th row is read data 
    IF (Row! = null ) 
    { 
        for ( int J =0 ; j <row.LastCellNum; ++ j)   // for each column worksheet 
        {
             String CellValue = row.GetCell (j) .ToString (); // Get i-th row j-th column data 
            Console.WriteLine (CellValue); 
        } 
    } 
} 
Console.ReadLine (); 
fileStream.Close (); 
workbook.Close ();

3.4 Excel style settings

  (1) Set the font

Style = workbook.CreateCellStyle ICellStyle (); // create a style object 
IFont font = workbook.CreateFont (); // create a font style object 
font.FontName = " Founder Shu body " ; // and excel inside the font corresponds 
font. = color new new HSSFColor.PIN.Index (); // color reference NPOI color table (see table reference Site (reference document 2)) 
font.IsItalic = to true ; // italic (? underlined) 
font.FontHeightInPoints = 16 ; // font size 
font.Boldweight = Short .MaxValue; // font bold 
style.SetFont (font); // will assign the font style style object
style = cell.CellStyle; // the pattern assigned cell

   (2) Set cell foreground

Style = ICellStyle workbook.CreateCellStyle (); 
style.FillForegroundColor = 14 ; // color numbers represent particular color look up table NPOI 
style.FillPattern = FillPatternType.SOLID_FOREGROUND; 

cellStyle.FillForegroundColor = HSSFColor.Blue.Index; // Check to text bACKGROUND 
cellStyle.FillBackgroundColor = HSSFColor.Red.Index; // check to cell background 
cellStyle.FillPattern = FillPattern.AltBars;

   (3) set the cell width and height

= row.Height 30 * 20 is ;     // line height, line-height 30 
sheet.SetColumnWidth ( . 3 , 13 * 256 )    // column width, column width of 4 to 13

   (4) merge cells

  After the cells merge, style, subject to the upper left cell.

sheet.AddMergedRegion ( new new CellRangeAddress ( 0 , 0 , 0 , 10 ));
 // CellRangeAddress four parameters: the start, the end of the row, starting column, the column end

   (5) cells horizontally aligned and centered

= style.Alignment HorizontalAlignment.CENTER; 
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left; // horizontally aligned 
style.VerticalAlignment = VerticalAlignment.Center; // vertically aligned

   (6) Set the formula

= cell.CellFormula " formula " ; // formula does not need to write the "="

   (7) to set the border

  They were set up and down the border style

style.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
style.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
style.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
style.BorderRight = NPOI.SS.UserModel.BorderStyle.THICK;

  Border color are provided up and down

style.TopBorderColor = HSSFColor.OliveGreen.Blue.Index;
style.BottomBorderColor = HSSFColor.OliveGreen.Blue.Index;
style.LeftBorderColor = HSSFColor.OliveGreen.Blue.Index;
style.RightBorderColor = HSSFColor.OliveGreen.Blue.Index;

   (8) Other

= cellStyle.WrapText to true ; // wrap 
cellStyle.Indention = 0 ; // indented 

3.5 class CSS with cell style Sets

  NPOI.CSS is a set NPOI can extend cell styles with CSS class method when using NPOI, support .NET4 and above project.

   (1) reference NPOI.CSS.dll

using NPOI.CSS;

   (2) Set cell style

cell.CSS("color:red;font-weight:bold;font-size:11;font-name:宋体;border-type:thin;");

  Specific style parameters, see Reference Site (reference documentation 3).

  (It seems difficult to find online resources NPOI.CSS.dll of a friend in need can Github (direct reference document 3) to find the source code, then compiled.)

 

Reference documents:

  1. Documents related to reading and writing:

  https://blog.csdn.net/dcrmg/article/details/52356236

  2. styling Related:

  https://www.cnblogs.com/nxxshxf/p/6410797.html

  https://blog.csdn.net/qq_35957944/article/details/85163316

  3. NPOI.CSS property:

  https://github.com/qihangnet/NPOI.CSS

 


Original Address: https://www.cnblogs.com/imdeveloper/p/10963364.html
please indicate the source, thank you!


 

Guess you like

Origin www.cnblogs.com/imdeveloper/p/10963364.html