Base solution for your next web application
Ends in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Export to Excel / Export to PDF #2647


User avatar
0
rev319303 created

Does anyone have any good examples of how to export data to an Excel document or how to Export a PDF?

In the past, I have always used the NPOI library to Export to Excel and iText to export a PDF but I don't think either of these work with ASP.NET Core.

I was hoping someone has already tackled this problem and had a good example they could share or some good links.

Thanks


2 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Current AspNet Zero Code templates has export to excel samples but we don't have any PDF samles. For the excel samples you can check our github repository.

  • User Avatar
    0
    rev319303 created

    Copying code example for others to see... <ins>EXPORT TO EXCEL</ins>

    JAVASCRIPT:

    $('#ExportUsersToExcelButton').click(function () {
                _userService
                    .getUsersToExcel({})
                    .done(function (result) {
                        app.downloadTempFile(result);
                    });
            });
    

    USER APP SERVICE:

    public async Task<FileDto> GetUsersToExcel()
            {
                var users = await UserManager.Users.Include(u => u.Roles).ToListAsync();
                var userListDtos = users.MapTo<List<UserListDto>>();
                await FillRoleNames(userListDtos);
    
                return _userListExcelExporter.ExportToFile(userListDtos);
            }
    

    USER LIST EXCEL EXPORTER:

    public FileDto ExportToFile(List<UserListDto> userListDtos)
            {
                return CreateExcelPackage(
                    "UserList.xlsx",
                    excelPackage =>
                    {
                        var sheet = excelPackage.Workbook.Worksheets.Add(L("Users"));
                        sheet.OutLineApplyStyle = true;
    
                        AddHeader(
                            sheet,
                            L("Name"),
                            L("Surname"),
                            L("UserName"),
                            L("PhoneNumber"),
                            L("EmailAddress"),
                            L("EmailConfirm"),
                            L("Roles"),
                            L("LastLoginTime"),
                            L("Active"),
                            L("CreationTime")
                            );
    
                        AddObjects(
                            sheet, 2, userListDtos,
                            _ => _.Name,
                            _ => _.Surname,
                            _ => _.UserName,
                            _ => _.PhoneNumber,
                            _ => _.EmailAddress,
                            _ => _.IsEmailConfirmed,
                            _ => _.Roles.Select(r => r.RoleName).JoinAsString(", "),
                            _ => _timeZoneConverter.Convert(_.LastLoginTime, _abpSession.TenantId, _abpSession.GetUserId()),
                            _ => _.IsActive,
                            _ => _timeZoneConverter.Convert(_.CreationTime, _abpSession.TenantId, _abpSession.GetUserId())
                            );
    
                        //Formatting cells
    
                        var lastLoginTimeColumn = sheet.Column(8);
                        lastLoginTimeColumn.Style.Numberformat.Format = "yyyy-mm-dd";
    
                        var creationTimeColumn = sheet.Column(10);
                        creationTimeColumn.Style.Numberformat.Format = "yyyy-mm-dd";
    
                        for (var i = 1; i <= 10; i++)
                        {
                            sheet.Column(i).AutoFit();
                        }
                    });
            }
    

    CREATE EXCEL PACKAGE:

    public IAppFolders AppFolders { get; set; }
    
            protected FileDto CreateExcelPackage(string fileName, Action<ExcelPackage> creator)
            {
                var file = new FileDto(fileName, MimeTypeNames.ApplicationVndOpenxmlformatsOfficedocumentSpreadsheetmlSheet);
    
                using (var excelPackage = new ExcelPackage())
                {
                    creator(excelPackage);
                    Save(excelPackage, file);
                }
    
                return file;
            }
    
            protected void AddHeader(ExcelWorksheet sheet, params string[] headerTexts)
            {
                if (headerTexts.IsNullOrEmpty())
                {
                    return;
                }
    
                for (var i = 0; i < headerTexts.Length; i++)
                {
                    AddHeader(sheet, i + 1, headerTexts[i]);
                }
            }
    
            protected void AddHeader(ExcelWorksheet sheet, int columnIndex, string headerText)
            {
                sheet.Cells[1, columnIndex].Value = headerText;
                sheet.Cells[1, columnIndex].Style.Font.Bold = true;
            }
    
            protected void AddObjects<T>(ExcelWorksheet sheet, int startRowIndex, IList<T> items, params Func<T, object>[] propertySelectors)
            {
                if (items.IsNullOrEmpty() || propertySelectors.IsNullOrEmpty())
                {
                    return;
                }
    
                for (var i = 0; i < items.Count; i++)
                {
                    for (var j = 0; j < propertySelectors.Length; j++)
                    {
                        sheet.Cells[i + startRowIndex, j + 1].Value = propertySelectors[j](items[i]);
                    }
                }
            }
    
            protected void Save(ExcelPackage excelPackage, FileDto file)
            {
                var filePath = Path.Combine(AppFolders.TempFileDownloadFolder, file.FileToken);
                excelPackage.SaveAs(new FileInfo(filePath));
            }
    

    If anyone else has a good PDF sample, it would be much appreciated. In the past, I would create a form fillable pdf and use iText to fill in the values for the pdf. I have also used iText to create the pdf from scratch. What I am trying to do is print off a "Course of Completion" pdf and fill in the users' details on the form fillable pdf. Any suggestions appreciated! Thanks!