ClosedXML導出Excel簡單使用


c#經常會用到導出excel。

ClosedXML是一個.NET庫,用於讀取,操作和寫入Excel 2007+(.xlsx,.xlsm)文件。它旨在提供一個直觀且用戶友好的interface來處理基礎的OpenXML API。

ClosedXML許可證是MIT

示例:

using ClosedXML.Excel;
using DoExcel.Models;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.IO;

namespace DoExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            List<User> list = new List<User>() {
                new User{ Name="Tom", Age=23 },
                new User{ Name="Jack", Age=25 },
                new User{ Name="Alice", Age=20 },
                new User{ Name="Jan", Age=24 },
            };
            Dictionary<string, string> map = new Dictionary<string, string>() {
                {"Name","姓名" },
                {"Age","年齡" },
            };
            File.WriteAllBytes("demo.xlsx", GetExcel(list, map, true));
        }

        private static byte[] GetExcel<T>(List<T> list, Dictionary<string, string> columnMap, bool useOrderNo = true)
        {
            using (var workbook = new XLWorkbook())
            {
                var worksheet = workbook.Worksheets.Add("sheet1");
                var propertyMap = typeof(T).GetProperties().ToDictionary(t => t.Name, t => t);

                int columnNum = 1;
                if (useOrderNo)
                {
                    worksheet.Cell(1, columnNum++).Value = "序號";
                }
                foreach (var item in columnMap)
                {
                    worksheet.Cell(1, columnNum++).Value = item.Value;
                }

                int row = 2;
                for (int i = 0; i < list.Count; i++, row++)
                {
                    var item = list[i];
                    int col = 1;
                    if (useOrderNo)
                    {
                        worksheet.Cell(row, col++).Value = i;
                    }
                    foreach (var column in columnMap)
                    {
                        worksheet.Cell(row, col++).Value = propertyMap[column.Key].GetValue(item);
                    }
                }

                using (var stream = new MemoryStream())
                {
                    workbook.SaveAs(stream);
                    return stream.ToArray();
                }

            }
        }
    }
}

需要注意的是Cell的行和列開始Index是1。在使用中遇到如下錯誤:

Row number must be between 1 and 1048576

Column number must be between 1 and 16384

由此可知,1<=行數<=1048576,1<=列數<=16384。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM