.Net Core 导入excel资源到数据库

2021/5/21 19:27:48

本文主要是介绍.Net Core 导入excel资源到数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.获取资源IFormFile file   2 转DataTable    3  预览  对比资源反馈 出来对比结果  4 保存  将有效结果保存

        /// <summary>
        /// 导入预览
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Task<List<ImportCheckDto>> ImportView(IFormFile file)
        {
            var dt = ExcelHelper.ToDataTable(file);
            return dispensingServices.ImportView(dt);
        }

 

 

 /// <summary>
        /// 上传文件转DT
        /// </summary>
        /// <param name="file"></param>
        /// <param name="hasTitle"></param>
        /// <returns></returns>
        public static DataTable ToDataTable(IFormFile file, bool hasTitle = true)
        {
            if (file == null || file.Length == 0) throw new UserException("请选择导入文件");
            CheckIsExcel(file.FileName);
            IWorkbook workBook = WorkbookFactory.Create(file.OpenReadStream(), ImportOption.All);

            ISheet sheet = workBook.GetSheetAt(0);

            DataTable dt = null;
            if (hasTitle)
            {
                dt = SheetToDataTableHasTitle(sheet);
            }
            else
            {
                dt = SheetToDataTable(sheet);
            }

            workBook.Close();
            return RemoveEmptyRow(dt);
        }

 

 

 /// <summary>
        /// 是否Excel文件
        /// </summary>
        /// <param name="fileName"></param>
        public static void CheckIsExcel(string fileName)
        {
            var allowExtension = new List<string>() { ".xlsx", ".xls" };
            var extension = Path.GetExtension(fileName);
            var fileOk = false;
            foreach (var item in allowExtension)
            {
                if (item.Equals(extension, StringComparison.InvariantCultureIgnoreCase)) fileOk = true;
            }
            if (!fileOk) throw new Exception("请选择EXCEL文件");
        }

 

 

 private static DataTable SheetToDataTableHasTitle(ISheet sheet)
        {
            DataTable dt = new DataTable();
            if (!string.IsNullOrWhiteSpace(sheet.SheetName))
            {
                dt.TableName = sheet.SheetName;
            }
            IRow firstRow = sheet.GetRow(0);
            if (firstRow != null)
            {
                for (int i = 0; i < firstRow.Cells.Count; i++)
                {
                    ICell cell = firstRow.GetCell(i);
                    if (cell != null)
                    {
                        var colName = firstRow.GetCell(i).ToString();
                        colName = Regex.Replace(colName, @"\s", "");
                        if (dt.Columns[colName] == null)
                        {
                            dt.Columns.Add(colName);
                        }
                        else
                        {
                            dt.Columns.Add();
                        }
                    }
                    else
                    {
                        dt.Columns.Add();
                    }
                }
                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dataRow = dt.NewRow();
                    IRow row = sheet.GetRow(i);
                    if (row == null)
                    {
                        continue;
                    }
                    for (int j = 0; j < firstRow.Cells.Count; j++)
                    {
                        ICell cell = row.GetCell(j);
                        if (cell == null)
                        {
                            dataRow[j] = "";
                            continue;
                        }

                        switch (cell.CellType)
                        {
                            case CellType.Boolean:
                                dataRow[j] = cell.BooleanCellValue;
                                break;
                            case CellType.Numeric:
                                //dataRow[j] = cell.NumericCellValue;
                                string value = string.Empty;
                                if (DateUtil.IsCellInternalDateFormatted(cell))
                                {
                                    value = DateTime.FromOADate(cell.NumericCellValue).ToString();
                                }
                                else if (DateUtil.IsCellDateFormatted(cell))
                                {
                                    value = DateTime.FromOADate(cell.NumericCellValue).ToString();
                                }
                                //有些情况,时间搓?数字格式化显示为时间,不属于上面两种时间格式
                                else if (cell.CellStyle.GetDataFormatString() == null)
                                {
                                    value = DateTime.FromOADate(cell.NumericCellValue).ToString();
                                }
                                else
                                {
                                    value = cell.NumericCellValue.ToString();
                                }
                                dataRow[j] = value;
                                break;
                            case CellType.String:
                                dataRow[j] = cell.StringCellValue.Trim();
                                break;
                            case CellType.Formula:
                                try
                                {
                                    dataRow[j] = cell.StringCellValue.Trim();
                                }
                                catch (Exception)
                                {
                                    try
                                    {
                                        dataRow[j] = cell.NumericCellValue;
                                    }
                                    catch (Exception)
                                    {
                                        dataRow[j] = cell.ToString().Trim();
                                    }
                                }
                                break;
                            default:
                                dataRow[j] = cell.ToString().Trim();
                                break;
                        }
                    }
                    dt.Rows.Add(dataRow);
                }
            }

            return dt;
        }

 

       /// <summary>
        /// NPOI Sheet转Datatable
        /// </summary>
        /// <param name="sheet"></param>
        /// <returns></returns>

   private static DataTable SheetToDataTable(ISheet sheet)
        {
            if (sheet.LastRowNum <= 0)
            {
                return null;
            }

            DataTable dt = new DataTable(sheet.SheetName);

            int maxColumnCount = 0;
            for (int i = 0; i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row == null || row.LastCellNum <= maxColumnCount)
                {
                    continue;
                }
                maxColumnCount = row.LastCellNum;
            }

            for (int i = 0; i < maxColumnCount; i++)
            {
                dt.Columns.Add();
            }

            for (int i = 0; i <= sheet.LastRowNum; i++)
            {
                DataRow dataRow = dt.NewRow();
                IRow row = sheet.GetRow(i);
                if (row == null)
                {
                    continue;
                }
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    ICell cell = row.GetCell(j);
                    if (cell == null)
                    {
                        dataRow[j] = "";
                        continue;
                    }

                    switch (cell.CellType)
                    {
                        case CellType.Boolean:
                            dataRow[j] = cell.BooleanCellValue;
                            break;
                        case CellType.Numeric:
                            dataRow[j] = cell.NumericCellValue;
                            break;
                        case CellType.String:
                            dataRow[j] = cell.StringCellValue.Trim();
                            break;
                        case CellType.Formula:
                            try
                            {
                                dataRow[j] = cell.StringCellValue.Trim();
                            }
                            catch (Exception)
                            {
                                try
                                {
                                    dataRow[j] = cell.NumericCellValue;
                                }
                                catch (Exception)
                                {
                                    dataRow[j] = cell.ToString().Trim();
                                }
                            }
                            break;
                        default:
                            dataRow[j] = cell.ToString().Trim();
                            break;
                    }
                }
                dt.Rows.Add(dataRow);
            }
            return dt;
        }

 



这篇关于.Net Core 导入excel资源到数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程