[EXCEL 최종 요약 공유] NPOI 확장을 바탕으로 봉인된 간이 조작 도구 라이브러리(간단하고 유연하며 사용하기 쉬우며 내보내기, 가져오기, 업로드 등 흔한 조작을 지원함)

37177 단어
EXCEL의 가져오기, 내보내기에 대해 나는 이전에 여러 차례 공유한 적이 있다. 예를 들어 다음과 같다.
첫 번째 방안: 은 주로 EXCEL을 DB로 삼아 데이터를 얻는 것이고 내보내는 것은 HTML TABLE로 연결하는 방식으로 ASP에서 사용할 수 있다.NET,ASP.NET CORE에서도 가능하며 간단하고 편리하며 Office Excel 구성 요소에 의존하여 사이트 서비스에만 적용됩니다.권장 지수:♥♥♥
두 번째 방안: 에서 데이터를 EXCEL로 내보내는 새로운 방법: 보기나 부분 보기를 HTML로 변환한 후 FileResult로 직접 되돌려줍니다. 이것은 주로 EXCEL을 내보내는 방법을 실현하고 MVC 프레임워크에 의존하여 보기 엔진을 이용하여 렌더링 뷰(view도 주로 HTML 표 템플릿)를 분석하여 HTML TABLE를 얻는 것입니다. 본질은 첫 번째 내보내기와 같습니다.다만 HTML TABLE를 코드로 연결하지 않고 View HTML 템플릿을 쓰면 됩니다. 간단하고 편리하며 ASP에 적용됩니다.NET MVC、ASP.NET MVC CORE;권장 지수:♥♥♥♥
세 번째 방안: 은 EXCEL의 유니버설 클래스를 가져오고 내보낼 수 있으며 참고로 WinForm 프로젝트에서 직접 사용할 수 있다. 이것은 EXCEL의 가져오기, 내보내기 방법을 실현하고 NPOI에 의존한다. 장점은 EXCEL을 설치하지 않아도 EXCEL을 조작할 수 있다는 것이다. 본고의 실현 방안과 예는 주로 C/S에 사용되고 B/S 지원이 우호적이지 않기 때문에 당연히 적당한 수정을 하면 WEB 버전을 호환할 수 있다.권장 지수:♥♥♥♥
네 번째 방안: 이라는 완벽한 유연성은 EXCEL의 각종 가져오기, 내보내기 방법을 실현했고 템플릿 내보내기, 포맷 사용자 정의 등 특징을 지원했다. 의존: Excel Report, NPOI, NPOI.Extend, C/S, B/S(C/S 특유의 방법 제외) 지원, 기업급 EXCEL 작업이 복잡한 장면에 적용: ExcelUtility, 추천 지수:♥♥♥♥♥,git 주소:https://gitee.com/zuowj/ExcelUtility
다섯 번째 방안: 바로 본고에서 소개하고자 하는 NPOI에 의존하여 EXCEL의 도입, 내보내기, 업로드 등 흔한 방법을 실현하고 세 번째, 네 번째 방안을 충분히 참고하여 핵심적인 실현 방법을 추출하고 적당한 개조를 해서 대부분의 EXCEL 장면을 만족시킨다. 가볍고 간단하며 사용하기 쉽다. 체인식 조작을 지원한다. 라이브러리 이름: ExcelEasyUtil,옛 이름: EXCEL 단순 실용 도구 라이브러리.
이 라이브러리는 주로 NPOI의 IWorkbook을 바탕으로 확장되고 확장 방법은 흔히 볼 수 있는 몇 가지 EXCEL을 내보내고 EXCEL 데이터를 가져오는 방법을 실현했다. 유형 집합을 바탕으로 하고 DataTable를 바탕으로 NPOIextensions의 완전한 실현 코드는 다음과 같다.
 
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq.Expressions;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;

namespace ExcelEasyUtil
{

    /// 
    /// NPOI   
    /// author:zuowenjun 
    /// 2019-5-21
    /// 
    public static class NPOIExtensions
    {
        /// 
        ///               EXCEL    (       sheet, :FillSheet(...).FillSheet(..) )
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IWorkbook FillSheet(this IWorkbook book, string sheetName, IList excelData,
            IList headerColNames, Func> getCellValuesFunc, IDictionary colDataFormats = null) where T : class
        {
            var sheet = book.CreateSheet(sheetName);

            IRow rowHeader = sheet.CreateRow(0);
            var headerCellStyle = GetCellStyle(book, true);
            Dictionary colStyles = new Dictionary();
            List colTypes = new List();
            Type strType = typeof(string);
            for (int i = 0; i < headerColNames.Count; i++)
            {
                ICell headerCell = rowHeader.CreateCell(i);
                headerCell.CellStyle = headerCellStyle;

                string colName = headerColNames[i];

                if (colName.Contains(":"))
                {
                    var colInfos = colName.Split(':');
                    colName = colInfos[0];
                    colTypes.Add(GetColType(colInfos[1]));
                }
                else
                {
                    colTypes.Add(strType);
                }

                headerCell.SetCellValue(colName);
                if (colDataFormats != null && colDataFormats.ContainsKey(colName))
                {
                    colStyles[i] = GetCellStyleWithDataFormat(book, colDataFormats[colName]);
                }
                else
                {
                    colStyles[i] = GetCellStyle(book);
                }
            }

            //  excel  
            for (int i = 0; i < excelData.Count; i++)
            {
                IRow irow = sheet.CreateRow(i + 1);
                var row = excelData[i];
                var cellValues = getCellValuesFunc(row);
                for (int j = 0; j < headerColNames.Count; j++)
                {
                    ICell cell = irow.CreateCell(j);
                    string cellValue = string.Empty;
                    if (cellValues.Count - 1 >= j && cellValues[j] != null)
                    {
                        cellValue = cellValues[j].ToString();
                    }

                    SetCellValue(cell, cellValue, colTypes[j], colStyles);
                }
            }

            return book;
        }

        /// 
        ///                EXCEL    (       sheet, :FillSheet(...).FillSheet(..) )
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IWorkbook FillSheet(this IWorkbook book, string sheetName, IList excelData,
                IDictionary>> colMaps, IDictionary colDataFormats = null
            ) where T : class
        {

            var sheet = book.CreateSheet(sheetName);

            var headerColNames = new List();
            var propInfos = new List();

            foreach (var item in colMaps)
            {
                headerColNames.Add(item.Key);
                var propInfo = GetPropertyInfo(item.Value);
                propInfos.Add(propInfo);
            }

            var headerCellStyle = GetCellStyle(book, true);
            Dictionary colStyles = new Dictionary();
            IRow rowHeader = sheet.CreateRow(0);
            for (int i = 0; i < headerColNames.Count; i++)
            {
                ICell headerCell = rowHeader.CreateCell(i);
                headerCell.CellStyle = headerCellStyle;
                headerCell.SetCellValue(headerColNames[i]);

                if (colDataFormats != null && colDataFormats.ContainsKey(headerColNames[i]))
                {
                    colStyles[i] = GetCellStyleWithDataFormat(book, colDataFormats[headerColNames[i]]);
                }
                else
                {
                    colStyles[i] = GetCellStyle(book);
                }
            }

            //  excel  
            for (int i = 0; i < excelData.Count; i++)
            {
                IRow irow = sheet.CreateRow(i + 1);
                var row = excelData[i];
                for (int j = 0; j < headerColNames.Count; j++)
                {
                    var prop = propInfos[j];

                    ICell cell = irow.CreateCell(j);
                    string cellValue = Convert.ToString(propInfos[j].GetValue(row, null));
                    SetCellValue(cell, cellValue, prop.PropertyType, colStyles);
                }
            }

            return book;
        }

        /// 
        ///       (DataTable)       EXCEL    (       sheet, :FillSheet(...).FillSheet(..) )
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IWorkbook FillSheet(this IWorkbook book, string sheetName, DataTable excelData, IDictionary colMaps,
            IDictionary colDataFormats = null)
        {

            if (excelData.Rows.Count <= 0) return book;

            var sheet = book.CreateSheet(sheetName);


            var headerCellStyle = GetCellStyle(book, true);
            Dictionary colStyles = new Dictionary();
            IRow rowHeader = sheet.CreateRow(0);

            int nIndex = 0;
            var headerColNames = new List();

            foreach (var item in colMaps)
            {
                ICell headerCell = rowHeader.CreateCell(nIndex);
                headerCell.SetCellValue(item.Value);
                headerCell.CellStyle = headerCellStyle;

                if (colDataFormats != null && colDataFormats.ContainsKey(item.Value))
                {
                    colStyles[nIndex] = GetCellStyleWithDataFormat(book, colDataFormats[item.Value]);
                }
                else
                {
                    colStyles[nIndex] = GetCellStyle(book);
                }
                headerColNames.Add(item.Key);
                nIndex++;
            }

            //  excel  
            for (int i = 0; i < excelData.Rows.Count; i++)
            {
                IRow irow = sheet.CreateRow(i + 1);
                var row = excelData.Rows[i];
                for (int j = 0; j < headerColNames.Count; j++)
                {
                    ICell cell = irow.CreateCell(j);
                    string colName = headerColNames[j];
                    string cellValue = row[colName].ToNotNullString();
                    SetCellValue(cell, cellValue, excelData.Columns[colName].DataType, colStyles);
                }
            }

            return book;
        }

        private static PropertyInfo GetPropertyInfo(Expression> select)
        {
            var body = select.Body;
            if (body.NodeType == ExpressionType.Convert)
            {
                var o = (body as UnaryExpression).Operand;
                return (o as MemberExpression).Member as PropertyInfo;
            }
            else if (body.NodeType == ExpressionType.MemberAccess)
            {
                return (body as MemberExpression).Member as PropertyInfo;
            }
            return null;
        }

        private static Type GetColType(string colTypeSimpleName)
        {
            colTypeSimpleName = colTypeSimpleName.ToUpper();
            switch (colTypeSimpleName)
            {
                case "DT":
                    {
                        return typeof(DateTime);
                    }
                case "BL":
                    {
                        return typeof(Boolean);
                    }
                case "NUM":
                    {
                        return typeof(Int64);
                    }
                case "DEC":
                    {
                        return typeof(Decimal);
                    }
                default:
                    {
                        return typeof(String);
                    }
            }
        }


        private static void SetCellValue(ICell cell, string value, Type colType, IDictionary colStyles)
        {
            if (colType.IsNullableType())
            {
                colType = colType.GetGenericArguments()[0];
            }

            string dataFormatStr = null;
            switch (colType.ToString())
            {
                case "System.String": //     
                    cell.SetCellType(CellType.String);
                    cell.SetCellValue(value);
                    break;
                case "System.DateTime": //    
                    DateTime dateV = new DateTime();
                    if (DateTime.TryParse(value, out dateV))
                    {
                        cell.SetCellValue(dateV);
                    }
                    else
                    {
                        cell.SetCellValue(value);
                    }
                    dataFormatStr = "yyyy/mm/dd hh:mm:ss";
                    break;
                case "System.Boolean": //   
                    bool boolV = false;
                    if (bool.TryParse(value, out boolV))
                    {
                        cell.SetCellType(CellType.Boolean);
                        cell.SetCellValue(boolV);
                    }
                    else
                    {
                        cell.SetCellValue(value);
                    }
                    break;
                case "System.Int16": //  
                case "System.Int32":
                case "System.Int64":
                case "System.Byte":
                    int intV = 0;
                    if (int.TryParse(value, out intV))
                    {
                        cell.SetCellType(CellType.Numeric);
                        cell.SetCellValue(intV);
                    }
                    else
                    {
                        cell.SetCellValue(value);
                    }
                    dataFormatStr = "0";
                    break;
                case "System.Decimal": //   
                case "System.Double":
                    double doubV = 0;
                    if (double.TryParse(value, out doubV))
                    {
                        cell.SetCellType(CellType.Numeric);
                        cell.SetCellValue(doubV);
                    }
                    else
                    {
                        cell.SetCellValue(value);
                    }
                    dataFormatStr = "0.00";
                    break;
                case "System.DBNull": //    
                    cell.SetCellType(CellType.Blank);
                    cell.SetCellValue(string.Empty);
                    break;
                default:
                    cell.SetCellType(CellType.Unknown);
                    cell.SetCellValue(value);
                    break;
            }

            if (!string.IsNullOrEmpty(dataFormatStr) && colStyles[cell.ColumnIndex].DataFormat <= 0) //    ,         
            {
                colStyles[cell.ColumnIndex] = GetCellStyleWithDataFormat(cell.Sheet.Workbook, dataFormatStr);
            }
            cell.CellStyle = colStyles[cell.ColumnIndex];

            ReSizeColumnWidth(cell.Sheet, cell);
        }


        private static ICellStyle GetCellStyleWithDataFormat(IWorkbook workbook, string format)
        {
            ICellStyle style = GetCellStyle(workbook);

            var dataFormat = workbook.CreateDataFormat();
            short formatId = -1;
            if (dataFormat is HSSFDataFormat)
            {
                formatId = HSSFDataFormat.GetBuiltinFormat(format);
            }
            if (formatId != -1)
            {
                style.DataFormat = formatId;
            }
            else
            {
                style.DataFormat = dataFormat.GetFormat(format);
            }
            return style;
        }


        private static ICellStyle GetCellStyle(IWorkbook workbook, bool isHeaderRow = false)
        {
            ICellStyle style = workbook.CreateCellStyle();

            if (isHeaderRow)
            {
                style.FillPattern = FillPattern.SolidForeground;
                style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
                IFont f = workbook.CreateFont();
                f.FontHeightInPoints = 11D;
                f.Boldweight = (short)FontBoldWeight.Bold;
                style.SetFont(f);
            }

            style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            return style;
        }

        private static void ReSizeColumnWidth(ISheet sheet, ICell cell)
        {
            int cellLength = (Encoding.Default.GetBytes(cell.ToString()).Length + 2) * 256;
            const int maxLength = 60 * 256; //255 * 256;
            if (cellLength > maxLength) //        30     (  60   )  ,     
            {
                cellLength = maxLength;
                cell.CellStyle.WrapText = true;
            }
            int colWidth = sheet.GetColumnWidth(cell.ColumnIndex);
            if (colWidth < cellLength)
            {
                sheet.SetColumnWidth(cell.ColumnIndex, cellLength);
            }
        }

        private static ISheet GetSheet(IWorkbook workbook, string sheetIndexOrName)
        {
            int sheetIndex = 0;
            ISheet sheet = null;

            if (int.TryParse(sheetIndexOrName, out sheetIndex))
            {
                sheet = workbook.GetSheetAt(sheetIndex);
            }
            else
            {
                sheet = workbook.GetSheet(sheetIndexOrName);
            }
            return sheet;
        }

        /// 
        ///          DataTable
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static DataTable ResolveDataTable(this IWorkbook workbook, string sheetIndexOrName, int headerRowIndex, short startColIndex = 0, short colCount = 0)
        {
            DataTable table = new DataTable();

            ISheet sheet = GetSheet(workbook, sheetIndexOrName);

            IRow headerRow = sheet.GetRow(headerRowIndex);
            int cellFirstNum = (startColIndex > headerRow.FirstCellNum ? startColIndex : headerRow.FirstCellNum);
            int cellCount = (colCount > 0 && colCount < headerRow.LastCellNum ? colCount : headerRow.LastCellNum);

            for (int i = cellFirstNum; i < cellCount; i++)
            {
                if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "")
                {
                    //          ,         
                    cellCount = i;
                    break;
                }
                DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                table.Columns.Add(column);
            }

            for (int i = (headerRowIndex + 1); i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row != null)
                {
                    List cellValues = new List();
                    for (int j = cellFirstNum; j < cellCount; j++)
                    {
                        if (row.GetCell(j) != null)
                        {
                            cellValues.Add(row.GetCell(j).ToNotNullString());
                        }
                        else
                        {
                            cellValues.Add(string.Empty);
                        }
                    }

                    table.Rows.Add(cellValues.ToArray());
                }
            }

            return table;
        }

        /// 
        ///                   
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static List ResolveAs(this IWorkbook workbook, string sheetIndexOrName, int headerRowIndex, Func, T> buildResultItemFunc,
            short startColIndex = 0, short colCount = 0)
        {
            ISheet sheet = GetSheet(workbook, sheetIndexOrName);

            IRow headerRow = sheet.GetRow(headerRowIndex);
            int cellFirstNum = (startColIndex > headerRow.FirstCellNum ? startColIndex : headerRow.FirstCellNum);
            int cellCount = (colCount > 0 && colCount < headerRow.LastCellNum ? colCount : headerRow.LastCellNum);

            List resultList = new List();
            for (int i = (headerRowIndex + 1); i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row != null)
                {
                    List cellValues = new List();
                    for (int j = cellFirstNum; j < cellCount; j++)
                    {
                        if (row.GetCell(j) != null)
                        {
                            cellValues.Add(row.GetCell(j).ToNotNullString());
                        }
                        else
                        {
                            cellValues.Add(string.Empty);
                        }
                    }

                    resultList.Add(buildResultItemFunc(cellValues));
                }
            }

            return resultList;
        }

        public static MemoryStream ToExcelStream(this IWorkbook book)
        {
            if (book.NumberOfSheets <= 0)
            {
                throw new Exception("    sheet  ");
            }

            MemoryStream stream = new MemoryStream();

            stream.Seek(0, SeekOrigin.Begin);
            book.Write(stream);

            return stream;
        }

        public static byte[] ToExcelBytes(this IWorkbook book)
        {
            using (MemoryStream stream = ToExcelStream(book))
            {
                return stream.ToArray();
            }
        }

        public static JObject HttpUpload(this IWorkbook book, string uploadUrl, IDictionary fieldData = null, string exportFileName = null)
        {
            using (HttpClient client = new HttpClient())
            {
                MultipartFormDataContent formData = new MultipartFormDataContent();
                ByteArrayContent fileContent = new ByteArrayContent(ToExcelBytes(book));
                //StreamContent fileContent = new StreamContent(ToExcelStream(book));      
                fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");

                if (string.IsNullOrWhiteSpace(exportFileName))
                {
                    exportFileName = Guid.NewGuid().ToString("N") + ((book is XSSFWorkbook) ? ".xlsx" : ".xls");
                }

                fileContent.Headers.ContentDisposition.FileName = exportFileName;
                fileContent.Headers.ContentDisposition.Name = "file";
                formData.Add(fileContent);

                Func getStringContent = (str) => new StringContent(str, Encoding.UTF8);

                if (fieldData != null)
                {
                    foreach (var header in fieldData)
                    {
                        formData.Add(getStringContent(header.Value.ToNotNullString()), header.Key);
                    }
                }


                HttpResponseMessage res = client.PostAsync(uploadUrl, formData).Result;
                string resContent = res.Content.ReadAsStringAsync().Result;
                return JObject.Parse(resContent);
            }
        }

        public static string SaveToFile(this IWorkbook book, string filePath)
        {
            if (File.Exists(filePath))
            {
                File.SetAttributes(filePath, FileAttributes.Normal);
                File.Delete(filePath);
            }

            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                book.Write(fs);
            }

            return filePath;
        }


    }

}

 
위의 코드는 모두 비교적 간단하고 복잡한 것이 없기 때문에 더 이상 상세하게 설명하지 않겠다.IWorkbook에 대한 사용자 정의 메소드가 있으면 사용하지 않을 수 있는 입구 도움말 클래스도 있습니다. 코드는 다음과 같습니다.
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Text;

namespace ExcelEasyUtil
{
    /// 
    /// NPOI            
    /// author:zuowenjun
    /// 2019-5-21
    /// 
    public static class Core
    {
        /// 
        ///       XLSX   EXCEL     
        /// 
        /// 
        public static IWorkbook CreateXlsxWorkBook()
        {
            return new XSSFWorkbook();
        }

        /// 
        ///       XLS   EXCEL     
        /// 
        /// 
        public static IWorkbook CreateXlsWorkBook()
        {
            return new HSSFWorkbook();
        }

        /// 
        ///        EXCEL     
        /// 
        /// Excel    
        /// 
        public static IWorkbook OpenWorkbook(string filePath)
        {
            bool isCompatible = filePath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);
            var fileStream = System.IO.File.OpenRead(filePath);
            if (isCompatible)
            {
                return new HSSFWorkbook(fileStream);
            }
            else
            {
                return new XSSFWorkbook(fileStream);
            }
        }

    }
}

코드는 간단하지만 방법의 명칭은 약간 중요하고 읽기 쉽고 이해하기 쉽다. CreateXlsxWorkBook은 xlsx격식을 기반으로 한 새로운 작업장 대상을 만드는 것을 나타낸다. CreateXlsWorkBook은 xls격식을 기반으로 한 작업장 대상을 만드는 것을 나타낸다. 나는 하나의 방법을 합성하지 않고 bool 매개 변수나 enum 매개 변수를 사용하여 구분한다.나는 이 간단하고 효율적인 개발 이념을 추구하는 과정에서 방법명은 이해하기 쉽고 신속하게 착수해야 하며 다른 뜻이 생겨서는 안 되고 너무 많은 파라미터가 필요하지 않다고 생각한다.OpenWorkbook은 기존의 EXCEL 파일 워크북을 열 수 있는 대상입니다.
코드는 간단하지만 저는 합리적인 인삼, 의뢰 파라미터 등을 통해 간단하면서도 유연성을 잃지 않는 EXCEL 조작 방식을 실현했습니다. 단순함을 추구하지 않고 모든 복잡한 조작을 모두 인삼함으로써 원래 간단한 일을 복잡하게 만들었습니다. 예를 들어 하나의 List를 EXCEL로 내보내는 것입니다.흔히 볼 수 있는 실현 방식은 반사를 통해 속성 정보를 얻고 속성 정보를 이용하여 값을 얻는 것이다. 이것은 입참이 간단하지만 성능이 좋지 않다. 본고의 이 라이브러리는 값을 얻거나 부여하는 방식을Func의뢰를 통해 구체적으로 사용하는 곳에 맡겨 반사로 인한 성능 손실을 피했다. 자, 다음과 같은 몇 가지 사용 예시를 보여준다.모두가 이해하고 사용하도록 돕다.
첫 번째 sheet 채우기 방식: (테이블 헤더의 매핑 설정에 중점을 두고 Lamba 속성 표현식을 통해 생성할 EXCEL 헤더와 관련 매핑)
var book= ExcelEasyUtil.Core.CreateXlsxWorkBook()
                .FillSheet("    1", peoples,//       
                //new Dictionary>> //     ,    
               new PropertyColumnMapping //     ,      
               {
                {"  ",p=>p.Name },{"  ",p=>p.Age },{"  ",p=>p.Birthday },{"  ",p=>p.Address },{"  ",p=>p.Education },
                { "    ",p=>p.hasWork },{"  ",p=>p.Remark }
               },
               new Dictionary //            
               {
                { "  ","0 "},{"  ","yyyy mm dd "}
               });

두 번째 sheet 채우기 방식: (표 헤더 형식 설정에 중점을 두고[:XXX는 생성된 EXCEL을 나타낸다. 이 열은 특정한 형식의 칸이다. 예를 들어 생일: DT는 생일을 표시하고 이 열은 날짜 형식 형식으로 내보낸다], 두 번째 파라미터는List를 되돌려줍니다. 이것은 내보낼 때 필요한 충전 데이터를 잘 제어할 수 있고 데이터를 자유롭게 제어할 수 있습니다. 예를 들어 예시 코드에 한 열로 판단된 데이터 열 내용을 추가했고 세 번째 파라미터는 지정한 열에 칸을 설정하는 구체적인 응용 격식입니다.
var book= ExcelEasyUtil.Core.CreateXlsxWorkBook() 
.FillSheet("    2", peoples,  //       
               new List
               {
                   "  ","  :NUM","  :DT","  ","  ","    :BL","  ","     "
               }, (p) =>
               {
                   return new List {
                       p.Name,p.Age,p.Birthday,p.Address,p.Education,p.hasWork?" ":" ",p.Remark,(p.Age<=30 && p.hasWork)?"    ":"         ,    "
                   };
               }, new Dictionary
               {
                   { "  ","yyyy-mm-dd"}
               });

세 번째 sheet 채우기 방식: (표두에 비치는 것이 중점이다. 이곳의 데이터 원본은 DataTable이기 때문에 DataTable의 열과 EXCEL에서 내보낼 열 이름만 비치면 된다. 열 유형을 지정할 필요가 없고 두 번째 파라미터는 지정한 열에 칸을 설정하는 구체적 응용 형식이다.)
var book= ExcelEasyUtil.Core.CreateXlsxWorkBook()  
 .FillSheet("    3", peoplesTable, //       
               new Dictionary {
                   {"Name","  " },{"Birthday","  " },{"Address","  " },{"Education","  " }, {"hasWork","    " },{"Remark","  " }
               }
               , new Dictionary
               {
                   { "  ","yyyy-mm-dd"}
               });

FillSheet 방법을 구현한 후에도 IWorkBook 인스턴스 자체로 되돌아오기 때문에 여러 개의 Sheet 내보내기를 체인식으로 신속하게 완성할 수 있습니다. 결합 코드는 다음과 같습니다.
 string savedPath = ExcelEasyUtil.Core.CreateXlsxWorkBook()
                .FillSheet("    1", peoples,//       
               //new Dictionary>> //     ,    
               new PropertyColumnMapping //     ,      
               {
                {"  ",p=>p.Name },{"  ",p=>p.Age },{"  ",p=>p.Birthday },{"  ",p=>p.Address },{"  ",p=>p.Education },
                { "    ",p=>p.hasWork },{"  ",p=>p.Remark }
               },
               new Dictionary //            
               {
                { "  ","0 "},{"  ","yyyy mm dd "}
               })
               .FillSheet("    2", peoples,  //       
               new List
               {
                   "  ","  :NUM","  :DT","  ","  ","    :BL","  ","     "
               }, (p) =>
               {
                   return new List {
                       p.Name,p.Age,p.Birthday,p.Address,p.Education,p.hasWork?" ":" ",p.Remark,(p.Age<=30 && p.hasWork)?"    ":"         ,    "
                   };
               }, new Dictionary
               {
                   { "  ","yyyy-mm-dd"}
               })
               .FillSheet("    3", peoplesTable, //       
               new Dictionary {
                   {"Name","  " },{"Birthday","  " },{"Address","  " },{"Education","  " }, {"hasWork","    " },{"Remark","  " }
               }
               , new Dictionary
               {
                   { "  ","yyyy-mm-dd"}
               })
               .SaveToFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "testdata123.xlsx"));

            Console.WriteLine("  EXCEL    :" + savedPath);

느낌이 어떻습니까? EXCEL은 열 헤더, 열 형식을 설정할 수 있을 뿐만 아니라 채워진 데이터 값도 제어할 수 있습니다. 저는 개인적으로 일상적인 대부분을 EXCEL을 사용하는 수요를 만족시킬 수 있다고 생각합니다.
EXCEL 내보내기 방법을 설명한 다음 EXCEL 데이터 가져오기(이곳은 해석 EXCEL 데이터라고 함)를 붙이는 예제 사용법을 설명합니다.
 var xlsTable = ExcelEasyUtil.Core.OpenWorkbook(savedPath).ResolveDataTable("    1", 0);
            foreach (DataRow row in xlsTable.Rows)
            {
                string rowStr = string.Join("\t", row.ItemArray);
                Console.WriteLine(rowStr);
            }

            var xlsPeoples = ExcelEasyUtil.Core.OpenWorkbook(savedPath).ResolveAs("    2", 0, list =>
            {
                return new People
                {
                    Name = list[0],
                    Birthday = ConvertToDate(list[2]),//         
                    Address = list[3]
                };
            }, 0, 4);

            Console.WriteLine("-".PadRight(30,'-'));
            foreach (var p in xlsPeoples)
            {
                string rowStr = string.Join("\t", p.Name, p.Age, p.Birthday, p.Address);
                Console.WriteLine(rowStr);
            }

여기서는 DataTable로 해석되거나 필요한 대상 집합으로 해석될 뿐 일반적인 데이터 가져오기 요구도 충족시킬 수 있다.
물론 Http Upload 방법은 생성된 메모리인 EXCEL 파일을 지정한 파일 서버에 직접 업로드하는 것입니다. 만약 ASP에 있다면.NET,ASP.NET CORE 서버에서 다운로드가 필요하면 먼저 사용할 수 있습니다: 책.ToExcelBytes () 를 만들고 파일 바이트 흐름 Result를 구성하면 됩니다. 예를 들어 MVC의 File은 본문에서 처음에 열거한 두 번째 방법의 도출을 참조할 수 있으며, 여기에 예시를 붙이지 않습니다.
자, 이상은 본고의 전체 내용입니다. 대신들은 이것이 너무 간단하다고 생각하지만 저는 간단하고 효율적인 실용 라이브러리가 필요하다고 생각합니다. Excel Easy Util 자체가 간단하고 가볍고 실용적이기 때문에 복잡한 것이 많지 않습니다. 만약에 복잡한 EXCEL 조작이 필요하다면 제가 말한 네 번째 방안인 Excel Utility를 사용하십시오.
부족한 점이나 좋은 건의가 있으면 댓글을 환영합니다. 감사합니다!
본 문서의 ExcelEasyUtil 소스 코드 주소:https://github.com/zuowj/ExcelEasyUtil(문장의 모든 예시 코드는github에 있음)
개발자가 편리하게 사용할 수 있도록 NuGet 패키지로 포장했습니다.
Packge Manager:Install-Package ExcelEasyUtil -Version 1.0.0
.NET CLI:dotnet add package ExcelEasyUtil --version 1.0.0 OR 

좋은 웹페이지 즐겨찾기