C # NPOI import and export Excel-compatible documents xlsx, xls (xf13 has been cited xlsx of npoi)

NPOI version used here is: 2.1.3.1

Official Download:  http://npoi.codeplex.com/releases

Version contains the .Net 2.0 and .Net 4.0

.Net 4.0 file contains

Need to be referenced when used to refer to all five dll

Use a reference to

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

 

After finishing as well as its own import and export Excel Code:

Copy the code

        /// <Summary> 
        /// introduced into Excel datable 
        /// </ Summary> 
        /// <name = "File" param> introduction path (including the file name and extension) </ param> 
        /// <Returns > </ Returns> 
        public static ExcelToTable the DataTable (String File) 
        { 
            the DataTable the DataTable dt = new new (); 
            IWorkbook Workbook; 
            String FileExt = Path.GetExtension (File) .ToLower (); 
            the using (the FileStream new new FS = the FileStream (File, FileMode .Open, FileAccess.Read)) 
            { 
                // XSSFWorkbook XLSX suitable format, HSSFWorkbook suitable format XLS
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                if (workbook == null) { return null; }
                ISheet sheet = workbook.GetSheetAt(0);

                //表头  
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        } 
                    } 
                    if (hasValue)
                    {
                        Dt.Rows.Add (DR); 
                    } 
                } 
            } 
            return dt; 
        } 

        /// <Summary> 
        /// datable exported to Excel 
        /// </ Summary> 
        /// <param name = "dt"> < / param> 
        /// <name = "file"> param export path (including the file name and extension) </ param> 
        public static void TableToExcel (the DataTable dt, String file) 
        { 
            IWorkbook Workbook; 
            String FileExt Path.GetExtension = ( file) .ToLower (); 
            IF (FileExt == ".xlsx" ) {workbook = new XSSFWorkbook () ;} else if (fileExt == ".xls") {workbook = new HSSFWorkbook ();} else {workbook = null;}
            if (workbook == null) { return; }
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);

            //表头  
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
            }

            //数据  
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }

            // into an array of bytes   
            MemoryStream Stream = new new MemoryStream (); 
            workbook.Write (Stream); 
            var buf = stream.ToArray (); 

            // saved as an Excel file   
            using (FileStream fs = new FileStream ( file, FileMode.Create , FileAccess.Write)) 
            { 
                fs.Write (buf, 0, buf.length); 
                fs.Flush (); 
            } 
        } 

        /// <Summary> 
        /// Get the cell type 
        /// </ Summary> 
        // / <param name = "Cell"> </ param> 
        /// <Returns> </ Returns> 
        Private static Object GetValueType (ICell Cell) 
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

Copy the code

Guess you like

Origin www.cnblogs.com/qqhfeng/p/11324225.html