SoFunction
Updated on 2025-04-06

C# uses NOPI library to import Excel documents

Import Excel Documents using NOPI

NOPI version: 2.3.0, SharpZipLib version that depends on NPOI: 0.86, tested for .net4.0+

Record several problems encountered

IWorkbook interface in: xls is implemented using HSSFWorkbook class, xlsx is implemented using XSSFWorkbook class

2. Date conversion, judge (j).CellType == && ((j)

Can't use (j).DateCellValue directly, this thing will throw an exception directly~

1. Convert file stream to DataTable

  /// <summary>
  /// Read Excel according to Excel format  /// </summary>
  /// <param name="stream">File Stream</param>  /// <param name="type">Excel format enumeration type, xls/xlsx</param>  /// <param name="sheetName">Table name, default to the first one</param>  /// &lt;returns&gt;DataTable&lt;/returns&gt;
  private static DataTable ImportExcel(Stream stream, ExcelExtType type, string sheetName)
  {
    DataTable dt = new DataTable();
    IWorkbook workbook;
    try
    {
      //xls is implemented using HSSFWorkbook class, xlsx is implemented using XSSFWorkbook class      switch (type)
      {
        case :
          workbook = new XSSFWorkbook(stream);
          break;
        default:
          workbook = new HSSFWorkbook(stream);
          break;
      }
      ISheet sheet = null;
      //Get the worksheet and get the first one by default      if ((sheetName))
        sheet = (0);
      else
        sheet = (sheetName);

      if (sheet == null)
        return null;
      IEnumerator rows = ();
      #region Get the table header      IRow headerRow = (0);
      int cellCount = ;
      for (int j = 0; j &lt; cellCount; j++)
      {
        ICell cell = (j);
        if (cell != null)
        {
          (());
        }
        else
        {
          ("");
        }
      }
      #endregion
      #region Get content      for (int i = ( + 1); i &lt;= ; i++)
      {
        IRow row = (i);
        DataRow dataRow = ();

        for (int j = ; j &lt; cellCount; j++)
        {
          if ((j) != null)
          {
            //Judge whether the cell is in date format            if ((j).CellType ==  &amp;&amp; ((j)))
            {
              if ((j). &gt;=1970)
              {
                dataRow[j] = (j).();
              }
              else
              {
                dataRow[j] = (j).ToString();

              }
            }
            else
            {
              dataRow[j] = (j).ToString();
            }
          }
        }
        (dataRow);
      }
      #endregion

    }
    catch (Exception ex)
    {
      dt=null;
    }
    finally
    {
      //if (stream != null)
      //{
      //  ();
      //  ();
      //}
    }
    return dt;
  }

2. File upload and import

  /// &lt;summary&gt;
  /// Upload Excel import  /// &lt;/summary&gt;
  /// <param name="file">Upload file object</param>  /// <param name="errorMsg">Error message</param>  /// <param name="sheetName">Table name, default to the first one</param>  /// &lt;returns&gt;&lt;/returns&gt;
  public static DataTable Import( file, ref string errorMsg, string sheetName = "")
  {
    if (file == null ||  == null ||  == 0)
    {
      errorMsg = "Please select the Excel file to import";
      return null;
    }
    var excelType = GetExcelFileType();
    if (excelType == null)
    {
      errorMsg = "Please select the correct Excel file";
      return null;
    }
    using (var stream = new MemoryStream())
    {
       = 0;
      (stream);
      var dt = ImportExcel(stream, , sheetName);
      if (dt == null)
        errorMsg = "Import failed, please select the correct Excel file";
      return dt;
    }
  }

3. Local path reading import
 

  /// &lt;summary&gt;
  /// Import Excel based on file path  /// &lt;/summary&gt;
  /// &lt;param name="filePath"&gt;&lt;/param&gt;
  /// <param name="errorMsg">Error message</param>  /// <param name="sheetName">Table name, default to the first one</param>  /// <returns>DataTable that may be null</returns>  public static DataTable Import(string filePath, ref string errorMsg, string sheetName = "")
  {
    var excelType = GetExcelFileType(filePath);
    if (GetExcelFileType(filePath) == null)
    {
      errorMsg = "Please select the correct Excel file";
      return null;
    }
    if (!(filePath))
    {
      errorMsg = "No Excel file to import was found";
      return null;
    }
    DataTable dt;
    using (var stream = new FileStream(filePath, , , ))
    {
      dt = ImportExcel(stream, , sheetName);
    }
    if (dt == null)
      errorMsg = "Import failed, please select the correct Excel file";
    return dt;
  }

4. Complete demo

A demo for importing Excel from winform.

/yimogit/NopiExcelDemo