C# under .Net develops controls for Excel (ClosedXML, EPPlus, NPOI)

C# under .Net develops controls for Excel (ClosedXML, EPPlus, NPOI)

https://www.cnblogs.com/ryantocode/p/excelwriter.html

Recently, the project needs a function of exporting Excel report. I searched it during the holidays and listed the more mainstream ones for reference only.

Functional Requirements:

  1. Create and write .xlsx Excel 2007+ spreadsheet files
  2. Office component support is not required, and the terminal computer does not need to install ms office
  3. Simple format, style, chart and formula support (without being too complicated), and the ability to insert images
  4. Speed, to ensure data writing speed in tables with more than 10,000 rows

Effect picture:  

 

1. ClosedXML

Homepage: https://github.com/ClosedXML/ClosedXML

You need to refer to OpenXMLSDK ( DocumentFormat.OpenXml.dll ) to operate files in a simple object-oriented way (similar to Visual Basic for Applications (VBA)), with complete documentation and examples

copy code

//create workbook
            using (var wb = new XLWorkbook(XLEventTracking.Disabled))
            {
                //Set the default Style
                var style = wb.Style;
                style.Font.FontName = "Microsoft YaHei";
                style.Font.FontSize = 11;

                //Add Sheets
                var ws = wb.Worksheets.Add("Sheet001");
                wb.Worksheets.Add("Sheet002");

                // Manual cell assignment
                ws.Cell(1, 1).Value = "Project";
                ws.Cell(1, 2).Value = "Project001";
                ws.Cell("A2").Value = "User";
                ws.Cell("B2").Value = "User001";
                ws.Cell(3, 1).SetValue("Create Date");
                ws.Cell(3, 2).SetValue(DateTime.Now);

                // Emphasize the first column of text
                var rngHeader = ws.Range(1, 1, 3, 1);
                rngHeader.Style
                    .Font.SetBold()
                    .Font.SetFontColor(XLColor.White)
                    .Fill.SetBackgroundColor(XLColor.SkyBlue)
                    .Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);

                //Merge cells
                ws.Cell(5, 1).Value = "Data List";
                var rngTitle = ws.Range(5, 1, 5, 5);
                rngTitle.Merge();//ws1.Row(5).Merge();
                rngTitle.Style
                    .Font.SetBold()
                    .Font.SetFontSize(15)
                    .Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
               
                //Insert table or data, set Timespan format
                var fakeData = Enumerable.Range(1, 5)
                    .Select(x => new FakeData
                    {
                        Time = TimeSpan.FromSeconds(x * 123.667),
                        X = x,
                        Y = -x,
                        Address = "a" + x,
                        Distance = x * 100
                    }).ToArray();

                var table = ws.Cell(6, 1).InsertTable(fakeData);
                table.Style.Font.FontSize = 9;
                var data = ws.Cell(13, 1).InsertData(fakeData);
                data.Style.Font.FontSize = 9;
                ws.Range(7, 1, 18, 1).Style.DateFormat.Format = "HH:mm:ss.000";

                //insert image
                var image = ws.AddPicture("1.png");
                image.MoveTo(ws.Cell(19, 1).Address);
                image.Scale(0.3);
                // adjust column spacing
                ws.Columns().AdjustToContents();//Will take twice as long to write data
                //save document
                wb.SaveAs("ClosedXML.xlsx");
            }

copy code

 

2. EPPlus

Homepage: https://github.com/JanKallman/EPPlus/

EPPlus does not need any other references, the documentation and examples are relatively complete

copy code

//create workbook
            using (var p = new ExcelPackage())
            {
                //Add Sheets
                var ws=  p.Workbook.Worksheets.Add("Sheet001");
                p.Workbook.Worksheets.Add("Sheet002");

                // Manual cell assignment
                ws.Cells[1,1].Value = "Project";
                ws.Cells[1, 2].Value = "Project001";
                ws.Cells["A2"].Value = "User";
                ws.Cells["B2"].Value = "User001";
                ws.Cells[3,1].Value = "Create Date";
                ws.Cells[3,2].Value = DateTime.Now;
                ws.Cells[3, 2].Style.Numberformat.Format = "YYYY/MM/DD";

                // Emphasize the first column of text
                var rngHeader = ws.Cells[1, 1, 3, 1];
                rngHeader.Style.Font.Bold = true;
                rngHeader.Style.Font.Color.SetColor(System.Drawing.Color.White);
                rngHeader.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                rngHeader.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.DodgerBlue);
                rngHeader.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                //Merge cells
                ws.Cells[5, 1].Value = "Data List";
                var rngTitle = ws.Cells[5, 1, 5, 5];
                rngTitle.Merge = true;
                rngTitle.Style.Font.Size = 15;
                rngTitle.Style.Font.Bold = true;
                rngTitle.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;


                //Insert table or data, set Timespan format
                var fakeData = Enumerable.Range(1, 5)
                    .Select(x => new FakeData
                    {
                        Time = TimeSpan.FromSeconds(x * 123.667),
                        X = x,
                        Y = -x,
                        Address = "a" + x,
                        Distance = x * 100
                    }).ToArray();

                ws.Cells[6, 1].LoadFromCollection(fakeData, true, OfficeOpenXml.Table.TableStyles.Medium27);
                ws.Cells[13, 1].LoadFromArrays(
                    fakeData.Select(x => new object[] {x.Time, x.X, x.Y, x.Address, x.Distance}));
                ws.Cells[6, 1, 18, 1].Style.Numberformat.Format = "HH:mm:ss.000";

                //insert image
                var image = ws.Drawings.AddPicture("picture", new FileInfo("1.png"));
                image.From.Row = 19;
                image.From.Column = 0;
                image.SetSize(30);
                //Set the default Style
                ws.Cells[ws.Dimension.Address].Style.Font.Name = "Microsoft YaHei";
                // adjust column spacing
                ws.Cells.AutoFitColumns(0);//It will take twice as long to write data
                //save document
                p.SaveAs(new FileInfo("EPPlus.xlsx"));
            }

copy code

 

3. NPOI

官网:https://github.com/tonyqus/npoi  .netcore version:https://github.com/dotnetcore/NPOI

Need to refer to SharpZipLib, can read and write Word and Excel, the examples are relatively complete, the system point of the document has not been found, but it is an open source project of the Chinese, Baidu should be able to find a lot

refer to:

http://blog.csdn.net/pan_junbiao/article/details/39717443   

http://www.cnblogs.com/yinrq/p/5590970.html 

http://www.cnblogs.com/hanzhaoxin/p/4232572.html  Report control based on NPIO

copy code

using (var fs = new FileStream("NPOI.xlsx", FileMode.Create, FileAccess.Write))
            {
                //create workbook
                IWorkbook wb = new XSSFWorkbook();

                //Add Sheets

                var ws = wb.CreateSheet("Sheet001");
                wb.CreateSheet("Sheet002");

                // Manual cell assignment
                ws.CreateRow(0).CreateCell(0).SetCellValue("Project");
                ws.CreateRow(0).CreateCell(1).SetCellValue("Project001");
                ws.CreateRow(1).CreateCell(0).SetCellValue("User");
                ws.CreateRow(1).CreateCell(1).SetCellValue("User001");
                ws.CreateRow(2).CreateCell(0).SetCellValue("Create Date");
                ws.CreateRow(2).CreateCell(1).SetCellValue(DateTime.Now);

                wb.Write(fs);
            }

copy code

4. Benchmarks

Simple test of the above three controls, 10,000 pieces of data are written

copy code

using (var wb = new XLWorkbook(XLEventTracking.Disabled))
            {
                var ws = wb.AddWorksheet("1");
                ws.Column(1).Style.DateFormat.Format = "HH:mm:ss.000";
                int rowCount = 1;
                foreach (var fakeData in data)
                {
                    rowCount++;
                    ws.Cell(rowCount, 1).Value = fakeData.Time;
                    ws.Cell(rowCount, 2).Value = fakeData.X;
                    ws.Cell(rowCount, 3).Value = fakeData.Distance;
                    ws.Cell(rowCount, 4).Value = fakeData.Address;
                }
                wb.SaveAs("ClosedXML.xlsx");
            }

            using (var wb = new ExcelPackage())
            {
                var ws = wb.Workbook.Worksheets.Add("1");
                ws.Column(1).Style.Numberformat.Format = "HH:mm:ss.000";
                ws.Cells[1, 1].LoadFromCollection(data,true,
                    OfficeOpenXml.Table.TableStyles.Medium2,
                    System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Instance,
                    new System.Reflection.MemberInfo[]
                    {
                        typeof(FakeData).GetProperty("Time"),
                        typeof(FakeData).GetProperty("X"),
                        typeof(FakeData).GetProperty("Distance"),
                        typeof(FakeData).GetProperty("Address")
                    });
                wb.SaveAs(new FileInfo("EPPlus.xlsx"));
            }

            using (var fs = new FileStream("NPOI.xlsx", FileMode.Create, FileAccess.Write))
            {
                var wb = new XSSFWorkbook();
                var ws = wb.CreateSheet("1");
                int rowCount = 0;
                IRow row;
                foreach (var fakeData in data)
                {
                    row = ws.CreateRow(rowCount++);
                    row.CreateCell(0).SetCellValue(fakeData.Time.ToString(@"hh\:mm\:ss\.fff"));
                    row.CreateCell(1).SetCellValue(fakeData.X);
                    row.CreateCell(2).SetCellValue(fakeData.Distance);
                    row.CreateCell(3).SetCellValue(fakeData.Address);
                }
                wb.Write(fs);
            }

copy code

BenchmarkDotNet=v0.10.9, OS=Windows 10 Redstone 2 (10.0.15063)
Processor=Intel Core i7-6700K CPU 4.00GHz (Skylake), ProcessorCount=8
Frequency=3914068 Hz, Resolution=255.4887 ns, Timer=TSC
  [Host]     : .NET Framework 4.7 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.2110.0
  Job-EJASFH : .NET Framework 4.7 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.2110.0
Method Mean Error StdDev Gen 0 Gen 1 Gen 2 Allocated
ClosedXML 337.6 ms NA 2.5647 ms 9625.0000 7062.5000 2812.5000 47.26 MB
EPPlus 145.8 ms NA 0.2533 ms 5000.0000 3250.0000 2000.0000 24.68 MB
NPOI 263.4 ms NA 5.8716 ms 10500.0000 7343.7500 2375.0000 55.65 MB

 

 

 

 

Overall, EPPlus is the best in terms of speed and memory. I feel that ClosedXML is more convenient for API calls, and the documentation is more comprehensive.

5. Others

The previous project used by SpreadSheetLight  , can read and write, requires OpenXMLSDK 2.5

ExcelDataReader  Excel 03-07 file reading, you only need to quickly read the excel file, you can use this

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325289819&siteId=291194637
Recommended