Excel operation using NPOI

Keywords: C# Excel

I. NPOI Component Import

Right-click item menu, "Manage NuGet package"

Direct search for "NPOI" will appear in the list, download the first installation can be done.

After installation, the following items will appear in the project reference

II. Basic Use

Add reference

using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

Excel operation begins

HSSFWorkbook hssfworkbook = new HSSFWorkbook();//First create Workbook
ISheet sheet= hssfworkbook.CreateSheet("Sheet1");//Establish sheet page
IRow row1=sheet.CreateRow(0);//Create row
row1.CreateCell(0).SetCellValue("test");//Create cells and set values

File export

FileStream file = new FileStream(sFilePath, FileMode.Create);
 hssfworkbook.Write(file);
 file.Close();

Style and Cell Operation

//Set column width (character width)
sheet.SetColumnWidth(0, 10 * 256);//First column, 10 character widths

//Set row height
row.HeightInPoints = 40;//Height (Pixels)

//Set the default row height and column box for the grid
sheet.DefaultColumnWidth=100*256;
sheet.DefaultRowHeightInPoints = 30;
//Setting Cell Style 

//Style creation
            ICellStyle style = hssfworkbook.CreateCellStyle();
            style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//The text is in the middle horizontally
            style.VerticalAlignment = VerticalAlignment.Center;//Vertical centering of words
            IFont font = hssfworkbook.CreateFont();//Typeface
            font.FontHeight = 20 * 20;
            style.SetFont(font);

            ICell cell = row.Cells[0];//Get the cell object
            cell.CellStyle = style;//Binding styles

Cell merging

//Cell merging
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0,0,0,8));//Combine A1 to I1

File Details Settings

 //Setting file details
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "Corporate name";//company
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = "theme";//theme
            hssfworkbook.DocumentSummaryInformation = dsi;
            hssfworkbook.SummaryInformation = si;

IV. Excel File Reading

//Obtain and read xls files according to paths
HSSFWorkbook wb = new HSSFWorkbook(new FileStream(@"C:\Users\Yc\Desktop\text.xls", FileMode.Open)); //Getting sheet objects ISheet sheet1 = wb.GetSheet("Sheet1");
//Get row
IRow row = sheet1.GetRow(0);
//Get cells
ICell cell = row1.GetCell(0);

After reading, the content can be operated on demand.

PS: Recently used, think about it or record it.

Posted by siric on Wed, 02 Oct 2019 06:02:47 -0700