SoFunction
Updated on 2025-03-07

C# uses NPOI to read excel to convert it to DataSet

This example shares the specific code of C# using NPOI to read excel into DataSet for your reference. The specific content is as follows

NPOI read excel to DataSet

/// <summary>
/// Read Execl data into DataTable(DataSet)/// </summary>
/// <param name="filePath">Specify Execl file path</param>/// <param name="isFirstLineColumnName">Set whether the first row is a column name</param>/// <returns>Return a DataTable dataset</returns>public static DataSet ExcelToDataSet(string filePath, bool isFirstLineColumnName)
   {
       DataSet dataSet = new DataSet();
       int startRow = 0;
       try
            {
                using (FileStream fs = (filePath))
                {
                    IWorkbook workbook = null;
                    // If it is the Excel version of 2007+                    if ((".xlsx") &gt; 0)
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    // If it is the Excel version of 2003-                    else if ((".xls") &gt; 0)
                    {
                            workbook = new HSSFWorkbook(fs);
                    }
                    if (workbook != null)
                    {
                        //Loop to read each sheet of Excel, each sheet page is converted to a DataTable and placed in the DataSet                        for (int p = 0; p &lt; ; p++)
                        {
                            ISheet sheet = (p);
                            DataTable dataTable = new DataTable();
                             = ;
                            if (sheet != null)
                            {
                                int rowCount = ;//Get the total number of rows                                if (rowCount &gt; 0)
                                {
                                    IRow firstRow = (0);//Get the first line                                    int cellCount = ;//Get the total number of columns
                                    //Build the column of datatable                                    if (isFirstLineColumnName)
                                    {
                                        startRow = 1;//If the first row is a column name, read from the second row                                        for (int i = ; i &lt; cellCount; ++i)
                                        {
                                            ICell cell = (i);
                                            if (cell != null)
                                            {
                                                if ( != null)
                                                {
                                                    DataColumn column = new DataColumn();
                                                    (column);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        for (int i = ; i &lt; cellCount; ++i)
                                        {
                                            DataColumn column = new DataColumn("column" + (i + 1));
                                            (column);
                                        }
                                    }

                                    //Fill the row                                    for (int i = startRow; i &lt;= rowCount; ++i)
                                    {
                                        IRow row = (i);
                                        if (row == null) continue;

                                        DataRow dataRow = ();
                                        for (int j = ; j &lt; cellCount; ++j)
                                        {
                                            ICell cell = (j);
                                            if (cell == null)
                                            {
                                                dataRow[j] = "";
                                            }
                                            else
                                            {
                                                //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
                                                switch ()
                                                {
                                                    case :
                                                        dataRow[j] = "";
                                                        break;
                                                    case :
                                                        short format = ;
                                                        //Terms of time formats (2015.12.5, 2015/12/5, 2015-12-5, etc.)                                                        if (format == 14 || format == 22 || format == 31 || format == 57 || format == 58)
                                                            dataRow[j] = ;
                                                        else
                                                            dataRow[j] = ;
                                                        break;
                                                    case :
                                                        dataRow[j] = ;
                                                        break;
                                                }
                                            }
                                        }
                                        (dataRow);
                                    }
                                }
                            }
                            (dataTable);
                        }

                    }
                }
                return dataSet;
            }
            catch (Exception ex)
            {
                var msg = ;
                return null;
            }
}

Dataset export to Excel

/// &lt;summary&gt;
/// Export DataTable(DataSet) to Execl document/// &lt;/summary&gt;
/// <param name="dataSet">Pass in a DataSet</param>/// <param name="Outpath">Export path (can be added without extension, without default to .xls)</param>/// <returns>Returns a Bool type value, indicating whether the export is successful</returns>/// True means export is successful, Flase means export failedpublic static bool DataTableToExcel(DataSet dataSet, string Outpath)
    {
            bool result = false;
            try
            {
                if (dataSet == null ||  == null ||  == 0 || (Outpath))
                    throw new Exception("Input DataSet or path exception");
                int sheetIndex = 0;
                //Judge the instance type of the workbook based on the extension of the output path                IWorkbook workbook = null;
                string pathExtensionName = ().Substring( - 5);
                if ((".xlsx"))
                {
                    workbook = new XSSFWorkbook();
                }
                else if((".xls"))
                {
                    workbook = new HSSFWorkbook();
                }
                else
                {
                    Outpath = () + ".xls";
                    workbook = new HSSFWorkbook();
                }
                //Export DataSet to Excel                foreach (DataTable dt in )
                {
                    sheetIndex++;
                    if (dt != null &amp;&amp;  &gt; 0)
                    {
                        ISheet sheet = (() ? ("sheet" + sheetIndex) : );//Create a table with the name Sheet0                        int rowCount = ;//Line Number                        int columnCount = ;//Number of columns
                        //Set the column header                        IRow row = (0);//The first row of excel is set as column header                        for (int c = 0; c &lt; columnCount; c++)
                        {
                            ICell cell = (c);
                            ([c].ColumnName);
                        }

                        //Set the cells of each row and column,                        for (int i = 0; i &lt; rowCount; i++)
                        {
                            row = (i + 1);
                            for (int j = 0; j &lt; columnCount; j++)
                            {
                                ICell cell = (j);//The second row of excel starts writing data                                ([i][j].ToString());
                            }
                        }
                    }
                }
                //Output data to outPath                using (FileStream fs = (Outpath))
                {
                    (fs);//Write data to the open xls file                    result = true;
                }
                return result;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }

Calling methods

DataSet set = ("", true);//Excel import  bool b = (set, "");//ExportExcel

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.