使用DocumentOpenXML、OfficeOpenXML、NPOI、EpPlus实现导入导出Excel表格

public class ExcelHelper
    {
        /// 
        /// 将数据导出为Excel文件
        /// 
        /// 文件名
        /// 数据
        /// 路径,默认D盘根目录
        /// 
        public string ExportExcel(string name, List strList, string path = "D:\\")
        {
            string documentPath = string.Format($"{path}{name}.xlsx");
            var spreadsheetDocument = SpreadsheetDocument.Create(documentPath, SpreadsheetDocumentType.Workbook);
            var workbookpart = spreadsheetDocument.AddWorkbookPart();
            workbookpart.Workbook = new Workbook();
            WorksheetPart worksheetPart = workbookpart.AddNewPart();
            worksheetPart.Worksheet = new Worksheet(new SheetData());
            Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
            Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };
            sheets.Append(sheet);
            var sheetData = worksheetPart.Worksheet.GetFirstChild();
            foreach (var item in strList)
            {
                Row row = new Row();
                foreach (var str in item)
                {
                    Cell dataCell = new Cell
                    {
                        CellValue = new CellValue(str),
                        DataType = new EnumValue(CellValues.String)
                    };
                    row.AppendChild(dataCell);
                }
                sheetData.Append(row);
            }

            workbookpart.Workbook.Save();
            spreadsheetDocument.Close();
            return documentPath;
        }
        
        /// 
        /// 读取Excel文件
        /// 
        /// 文件路径
        public List ImportExcel(string path)
        {
            using (SpreadsheetDocument doc = SpreadsheetDocument.Open(path, false))
            {
                WorkbookPart wbPart = doc.WorkbookPart;
                SharedStringTablePart tablePart = wbPart.SharedStringTablePart;
                Sheet mysheet = (Sheet)doc.WorkbookPart.Workbook.Sheets.ChildElements.FirstOrDefault();
                WorksheetPart worksheet = ((WorksheetPart)wbPart.GetPartById(mysheet.Id));
                SheetData sheetData = worksheet.Worksheet.GetFirstChild();
                List strList = new List();
                ArrayList arrayList = new ArrayList();
                foreach (var row in sheetData.ChildElements)
                {
                    foreach (var cell in (row as Row).ChildElements)
                    {
                        var cellValue = (cell as Cell).CellValue;
                        if (cellValue != null)
                        {
                            arrayList.Add(GetValue((cell as Cell), tablePart));
                        }
                    }
                    string[] arrString = (string[])arrayList.ToArray(typeof(string));
                    strList.Add(arrString);
                    arrayList.Clear();
                    arrString = null;
                }
                return strList;
            }
        }
        
        /// 
        /// 读取s类型的列(SharedStringTable类型),它的值是存储在子元素内的。
        /// 
        /// 单元格
        /// WorkbookPart.SharedStringTablePart
        /// 
        public static String GetValue(Cell cell, SharedStringTablePart stringTablePart)
        {
            if (cell.ChildElements.Count == 0)

                return null;

            String value = cell.CellValue.InnerText;


            if ((cell.DataType != null) && (cell.DataType == CellValues.SharedString))

                value = stringTablePart.SharedStringTable

                .ChildElements[Int32.Parse(value)]

                .InnerText;

            return value;

        }
        
        /// 
        /// 读取Excel数据(OfficeOpenXML)
        /// 
        /// 
        /// 
        public List ImportExcel(string path)
        {
            var file = new FileInfo(path);
            var strList = new List();
            var arrayList = new ArrayList();
            if (file != null)
            {
                using (ExcelPackage package = new ExcelPackage(file))
                {

                    var worksheet = package.Workbook.Worksheets[0];
                    //获取表格的列数和行数
                    var rowCount = worksheet.Dimension.Rows;
                    var ColCount = worksheet.Dimension.Columns;
                    for (int row = 1; row <= rowCount; row++)
                    {
                        for(int cel = 1; cel <= ColCount; cel++)
                        {
                            arrayList.Add(worksheet.Cells[row, cel].Value.ToString());
                        }
                        var arrString = (string[])arrayList.ToArray(typeof(string));
                        strList.Add(arrString);
                        arrayList.Clear();
                        arrString = null;

                    }
                    return strList;
                }
            }
            return null;
        }
        
        /// 
        /// 读取Excel文件(NPOI) 
        /// 
        /// 
        /// 
        public List ImportExcel_NPOI(string path)
        {
            var arrayList = new ArrayList();
            var strList = new List();
            var dt = new DataTable();
            IWorkbook workbook;
            var fileExt = Path.GetExtension(path).ToLower();
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx")
                {
                    workbook = new XSSFWorkbook(fs);
                }
                else if (fileExt == ".xls")
                {
                    workbook = new HSSFWorkbook(fs);
                }
                else
                {
                    workbook = null;
                }

                if (workbook == null) { return null; }


                var sheet = workbook.GetSheetAt(0);

                //表头  
                var header = sheet.GetRow(sheet.FirstRowNum);
                var columns = new List();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    var 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);
                    arrayList.Add(obj.ToString());
                }

                var arrString = (string[])arrayList.ToArray(typeof(string));
                strList.Add(arrString);
                arrayList.Clear();
                arrString = null;

                //数据  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    var dr = dt.NewRow();
                    var 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;
                            arrayList.Add(dr[j]);
                        }
                    }
                    if (hasValue)
                    {
                        arrString = (string[])arrayList.ToArray(typeof(string));
                        strList.Add(arrString);
                        arrayList.Clear();
                        arrString = null;
                    }
                }
            }
            return strList;
        }

        /// 
        /// 获取单元格类型
        /// 
        /// 
        /// 
        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;
            }
        }
    }



【EPPLUS】
 public class OfficeHelper where T : new()
    {
        /// 
        /// 获取 Excel Sheet 数据集合
        /// 
        /// 文件路径
        /// 
        public T[] GetSheetValues(string path)
        {
            var file = new FileInfo(path);
            if (file == null) return null;

            using (var package = new ExcelPackage(file))
            {
                var worksheet = package.Workbook.Worksheets.First();

                var result = worksheet.ConvertSheetToObjects().ToArray();
                return result;
            }
        }
    }

    public class Excels
    {
        /// 
        /// 分别对应表中的列名
        /// 
        [ExcelColumn("Name")]
        public string Name { get; set; }
        [ExcelColumn("Level")]
        public string Level { get; set; }
        [ExcelColumn("Sort")]
        public string Sort { get; set; }
        [ExcelColumn("Code")]
        public string Code { get; set; }
        [ExcelColumn("Type")]
        public string Type { get; set; }


        //存储表格数据归属关系
        public int Index { get; set; }
    }

    /// 
    /// 自定义excel头部标签
    /// 
    [AttributeUsage(AttributeTargets.All)]
    public class ExcelColumn : Attribute
    {
        /// 
        /// 标签名称
        /// 
        public string ColumnName { get; set; }

        /// 
        /// 构造函数
        /// 
        /// 
        public ExcelColumn(string name)
        {
            ColumnName = name;
        }
    }

    public static class EpplusExtensions
    {
        /// 
        /// 获取标签对应excel的Index
        /// 
        /// 
        /// 
        /// 
        /// 
        public static int GetColumnByName(this ExcelWorksheet ws, string columnName)
        {
            if (ws == null) throw new ArgumentNullException(nameof(ws));
            return ws.Cells["1:1"].FirstOrDefault(c => c.Value.ToString() == columnName).Start.Column;
        }
        /// 
        /// 扩展方法,转换为实体列表
        /// 
        /// 
        /// 
        /// 
        public static IEnumerable ConvertSheetToObjects(this ExcelWorksheet worksheet) where T : new()
        {

            bool columnOnly(CustomAttributeData y) => y.AttributeType == typeof(ExcelColumn);

            var rows = worksheet.Cells
                .Select(cell => cell.Start.Row)
                .Distinct()
                .OrderBy(x => x);

            var columns = typeof(T)
                .GetProperties()
                .Where(x => x.CustomAttributes.Any(columnOnly))
                .Select(p => new
                {
                    Property = p,
                    Column = p.GetCustomAttributes().First().ColumnName
                }).ToList();

            var str = "";
            var index = worksheet.Cells["1:1"].Last().Start.Column;
            for (int i = 1; i <= index; i++)
            {
                var result = worksheet.Cells[1, i].Value.ToString();
                str += result;
            }

            var collection = rows.Skip(1)
                .Select(row =>
                {
                    var tnew = new T();
                    columns.ForEach(col =>
                    {
                        if (-1 != str.IndexOf(col.Column))
                        {
                            var val = worksheet.Cells[row, GetColumnByName(worksheet, col.Column)];
                            if (val.Value == null)
                            {
                                col.Property.SetValue(tnew, null);
                                return;
                            }
                            col.Property.SetValue(tnew, val.GetValue());
                        }

                    });

                    return tnew;
                });
            return collection;
        }
    }

你可能感兴趣的:(学习笔记)