国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > C# > 正文

C#使用NOPI庫(kù)實(shí)現(xiàn)導(dǎo)入Excel文檔

2019-10-29 21:11:06
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

使用NOPI導(dǎo)入Excel文檔

NOPI版本:2.3.0,依賴(lài)于NPOI的SharpZipLib版本:0.86,經(jīng)測(cè)試適用于.net4.0+

記錄遇到的幾個(gè)問(wèn)題

1.NOPI中的IWorkbook接口:xls使用HSSFWorkbook類(lèi)實(shí)現(xiàn),xlsx使用XSSFWorkbook類(lèi)實(shí)現(xiàn)

2.日期轉(zhuǎn)換,判斷row.GetCell(j).CellType == NPOI.SS.UserModel.CellType.Numeric && HSSFDateUtil.IsCellDateFormatted(row.GetCell(j)

不能直接使用row.GetCell(j).DateCellValue,這玩意會(huì)直接拋出異常來(lái)~

1. 將文件流轉(zhuǎn)換為DataTable

  /// <summary>  /// 根據(jù)Excel格式讀取Excel  /// </summary>  /// <param name="stream">文件流</param>  /// <param name="type">Excel格式枚舉類(lèi)型,xls/xlsx</param>  /// <param name="sheetName">表名,默認(rèn)取第一張</param>  /// <returns>DataTable</returns>  private static DataTable ImportExcel(Stream stream, ExcelExtType type, string sheetName)  {    DataTable dt = new DataTable();    IWorkbook workbook;    try    {      //xls使用HSSFWorkbook類(lèi)實(shí)現(xiàn),xlsx使用XSSFWorkbook類(lèi)實(shí)現(xiàn)      switch (type)      {        case ExcelExtType.xlsx:          workbook = new XSSFWorkbook(stream);          break;        default:          workbook = new HSSFWorkbook(stream);          break;      }      ISheet sheet = null;      //獲取工作表 默認(rèn)取第一張      if (string.IsNullOrWhiteSpace(sheetName))        sheet = workbook.GetSheetAt(0);      else        sheet = workbook.GetSheet(sheetName);      if (sheet == null)        return null;      IEnumerator rows = sheet.GetRowEnumerator();      #region 獲取表頭      IRow headerRow = sheet.GetRow(0);      int cellCount = headerRow.LastCellNum;      for (int j = 0; j < cellCount; j++)      {        ICell cell = headerRow.GetCell(j);        if (cell != null)        {          dt.Columns.Add(cell.ToString());        }        else        {          dt.Columns.Add("");        }      }      #endregion      #region 獲取內(nèi)容      for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)      {        IRow row = sheet.GetRow(i);        DataRow dataRow = dt.NewRow();        for (int j = row.FirstCellNum; j < cellCount; j++)        {          if (row.GetCell(j) != null)          {            //判斷單元格是否為日期格式            if (row.GetCell(j).CellType == NPOI.SS.UserModel.CellType.Numeric && HSSFDateUtil.IsCellDateFormatted(row.GetCell(j)))            {              if (row.GetCell(j).DateCellValue.Year >=1970)              {                dataRow[j] = row.GetCell(j).DateCellValue.ToString();              }              else              {                dataRow[j] = row.GetCell(j).ToString();              }            }            else            {              dataRow[j] = row.GetCell(j).ToString();            }          }        }        dt.Rows.Add(dataRow);      }      #endregion    }    catch (Exception ex)    {      dt=null;    }    finally    {      //if (stream != null)      //{      //  stream.Close();      //  stream.Dispose();      //}    }    return dt;  }

2. 文件上載導(dǎo)入

  /// <summary>  /// 上傳Excel導(dǎo)入  /// </summary>  /// <param name="file">上載文件對(duì)象</param>  /// <param name="errorMsg">錯(cuò)誤信息</param>  /// <param name="sheetName">表名,默認(rèn)取第一張</param>  /// <returns></returns>  public static DataTable Import(System.Web.HttpPostedFileBase file, ref string errorMsg, string sheetName = "")  {    if (file == null || file.InputStream == null || file.InputStream.Length == 0)    {      errorMsg = "請(qǐng)選擇要導(dǎo)入的Excel文件";      return null;    }    var excelType = GetExcelFileType(file.FileName);    if (excelType == null)    {      errorMsg = "請(qǐng)選擇正確的Excel文件";      return null;    }    using (var stream = new MemoryStream())    {      file.InputStream.Position = 0;      file.InputStream.CopyTo(stream);      var dt = ImportExcel(stream, excelType.Value, sheetName);      if (dt == null)        errorMsg = "導(dǎo)入失敗,請(qǐng)選擇正確的Excel文件";      return dt;    }  }

3. 本地路徑讀取導(dǎo)入
 

  /// <summary>  /// 根據(jù)文件路徑導(dǎo)入Excel  /// </summary>  /// <param name="filePath"></param>  /// <param name="errorMsg">錯(cuò)誤信息</param>  /// <param name="sheetName">表名,默認(rèn)取第一張</param>  /// <returns>可能為null的DataTable</returns>  public static DataTable Import(string filePath, ref string errorMsg, string sheetName = "")  {    var excelType = GetExcelFileType(filePath);    if (GetExcelFileType(filePath) == null)    {      errorMsg = "請(qǐng)選擇正確的Excel文件";      return null;    }    if (!File.Exists(filePath))    {      errorMsg = "沒(méi)有找到要導(dǎo)入的Excel文件";      return null;    }    DataTable dt;    using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))    {      dt = ImportExcel(stream, excelType.Value, sheetName);    }    if (dt == null)      errorMsg = "導(dǎo)入失敗,請(qǐng)選擇正確的Excel文件";    return dt;  }

4.完整demo

附贈(zèng)一個(gè)winform導(dǎo)入Excel的Demo。

https://github.com/yimogit/NopiExcelDemo


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到c#教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 常州市| 鲜城| 凤城市| 香格里拉县| 土默特左旗| 龙岩市| 德保县| 新昌县| 称多县| 保定市| 历史| 会泽县| 江安县| 威信县| 仪陇县| 沅陵县| 淮南市| 昭苏县| 扶沟县| 迁西县| 蕲春县| 五常市| 永兴县| 乳源| 娱乐| 卫辉市| 拜城县| 突泉县| 阳新县| 安溪县| 谷城县| 集安市| 北京市| 抚顺市| 紫云| 涟源市| 商城县| 滨州市| 涟源市| 海宁市| 大安市|