ASP.NET Core import and export Excel using EPPlus

The development process, often encounter import and export data needs, this blog explains how to use EPPlus components in .NET Core import and export in Excel

EPPlus:

EPPlus is using Open Office XML format (xlsx) .net development library to read and write Excel 2007/2010 files, can read and write Excel 2007/2010 file that can run on Windows, Linux and Mac, the official website address: HTTPS: // Archive. codeplex.com/

In the .net core can also be used NOPI operating Excel, this does not describe.

Use EPPlus Operation Excel:

1, the introduction EPPlus package , run the installation package dependencies in the Management Console:

1 PM> Install-Package EPPlus.Core -Version 1.5.4

2, export Excel 

① When using EF Core operating database, the data set used to facilitate export List.

② injection IHostingEnvironment in the constructor of the controller to get the site's root directory path, in order to set export Excel file path.

. 1  public IActionResult OutputExcel ( )
 2 {
 . 3      // Data Source list is set 
. 4      var Query = ( from U in _context.UserInfo
 . 5                   SELECT  new new 
. 6                   {
 . 7                       u.UId,
 . 8                       u.UName,
 . 9                       u.UPws,
 10                       U. UEmail,
 . 11                       u.UTel
 12 is                   .}) ToList ();
 13 is      // specified export Excel file path 
14      String= sWebRootFolder _hostingEnv.WebRootPath;
 15      // filename 
16      String sFileName = $ @ " Test Export DateTime.Now.ToString {( " yyyyMMddHHmmss " )} XLSX. " ;
 . 17      // The two strings into a path 
18 is      var = path Path.Combine (sWebRootFolder, sFileName);
 19      // create a file object 
20      FileInfo file = new new FileInfo (path);
 21      // If the file exists 
22      IF (the File.exists)
 23      {
 24-          // delete files 
25         File.Delete ();
 26 is          // re-create the file objects 
27          File = new new the FileInfo (path);
 28      }
 29      // Create Object ExcelPackage 
30      the using (ExcelPackage Package = new new ExcelPackage (File))
 31 is      {
 32          // Add New sheet to the workbook 
33 is          ExcelWorksheet worksheet = package.Workbook.Worksheets.Add ( " the UserInfo " );
 34 is          // the list set loaded onto the work table, the print head table 
35          worksheet.Cells.LoadFromCollection (Query, to true );
 36          / / save Excel
37 [          package.Save (); 
 38 is      } // release resources 
39      return View ( " Index " );
 40 }

ExcelPackage inlet EPPlus class is class, parses an Excel file, represents an object to generate ExcelWorkbook Excel.

ExcelPackage class implements IDisposable, you can use using object-release.

ExcelWorksheet class can be set to Excel table style, but set the Excel spreadsheet style will increase the burden of memory, the export may slow down.

3, import Excel

Import, export Excel method, bloggers are using the Ajax request, when importing Excel, fackpath path problem will occur when incoming spool file path, file after the first imported directly saved in the root directory, and then import the root directory files

JavaScript code: 

. 1 $ ( "# IExcel") the Click (. Function () {
 2      var FormData = new new FormData (); // Create an empty object FormData by the constructor 
. 3      formdata.append ( 'File', $ ( "# Import") [0] .files [0]); // be added by the append () method of the data 
. 4      $ .ajax ({
 . 5          type: "POST" ,
 . 6          URL: "/ the Main / ImportExcel" ,
 . 7          contentType: to false , // Do not request to set Content-Type header 
. 8          the processData: to false , // do not process data to be transmitted 
. 9          data: FormData,
 10         success: function (data) {
11             alert(data.message);                        
12         },
13         error: function () {
14             alert("导入失败!");
15         }
16     })                
17 })

When using FormData object transmission data shall be provided to the browser not to process the data and settings request sent Content-Type header, otherwise the error JS: Uncaught TypeError: Illegal invocation

C # code: 

. 1  public IActionResult ImportExcel ()
 2 {
 . 3      the try 
. 4      {
 . 5          // file to import first uploaded to the root directory
 6          // Get pass over the front end of the file 
. 7          var Files = Request.Form.Files;
 . 8          var filePath = "" ;
 . 9          the foreach ( var Item in files)
 10          {
 . 11              // get file name 
12 is              filePath = item.FileName;
 13 is              // specified file upload path 
14             = + $ _hostingEnv.WebRootPath filePath @ " \ {filePath} " ;
 15              // create a stream file 
16              the using (FS = the FileStream System.IO.File.Create (filePath))
 . 17              {
 18 is                  // Copy the contents of the file to upload stream object 
. 19                  item.CopyTo (FS);
 20 is                  // clear the buffer for this flow and cause any data is written to the buffer 
21 is                  fs.Flush ();
 22 is              }
 23 is          }
 24          // Create a file object 
25          the FileInfo file = new new the FileInfo (filePath);
 26          IF (File =!null )
 27          {
 28              // create objects ExcelPackage 
29              the using (ExcelPackage Package = new new ExcelPackage (File))
 30              {
 31 is                  // access Excel table the first table 
32                  ExcelWorksheet package.Workbook.Worksheets Worksheet = [ . 1 ];
 33 is                  // number of rows acquired table 
34 is                  int the rowCount = worksheet.Dimension.Rows;
 35                  // number of columns of the table acquired 
36                  int ColCount = worksheet.Dimension.Columns;
 37 [                  var User = new new List<UserInfo>();
38                 for (int row = 1; row <= rowCount; row++)
39                 {
40                     UserInfo userinfo = new UserInfo();
41                     //指定行列赋值
42                     userinfo.UName = worksheet.Cells[row, 2].Value.ToString();
43                     userinfo.UPws = worksheet.Cells[row, 3].Value.ToString();
44                     userinfo.UEmail = worksheet.Cells[row, 4].Value.ToString();
45                     = worksheet.Cells userinfo.UTel [Row, . 5 ] .Value.ToString ();
 46 is                      // save data to entity 
47                      _context.UserInfo.Add (UserInfo);
 48                      _context.SaveChanges ();
 49                  }
 50                  return Json ( new new {Message = " import successful! " });
 51 is              }
 52 is          }
 53 is          return  null ;
 54 is      }
 55      the catch (Exception EX)
 56 is      {
 57 is          return Json (new new {Message = " Import failed! " + EX});
 58      }
 59 }

ExcelWorkbook class represents an Excel document, which corresponds to the respective Worksheets Sheet properties of Excel. Worksheets property is automatically created, do not worry null pointer exception, but the Count may be zero. Note: When obtaining specific Sheet, the index number starting at 1.

End!

Guess you like

Origin www.cnblogs.com/gygg/p/11422959.html