Home > Enterprise >  How to add multiple worksheets in workbook C#
How to add multiple worksheets in workbook C#

Time:03-01

I am trying to generate multiple worksheets for every student in my list but not sure how to achieve this,i can generate Excel document with one worksheet successfully but shows all students in one sheet,how can i generate a new sheet for every student?i tried achieving this with the code below thanks.

 public FileContentResult GenerateStudentReport([FromForm] Student Students)
        {
                int count = 0;
                Workbook workbook = new Workbook();
                Worksheet worksheet;
                foreach (var item in Students)
                {
                    worksheet = workbook.Worksheets[count];
               
                    var dataSet = new DataSet();
                    // Add the new DataTable to the DataSet.
                    dataSet.Tables.Add(table);

                    row["studentid"] = Convert.ToString(item.id);
                    row["studentName"] = Convert.ToString(item.Name);
                    row["studentSurname"] = Convert.ToString(item.Surname);...
                    table.Rows.Add(row);

                    worksheet[count].Import(table, true, 0, 0);
                    worksheet[count]["A1:V1"].Font.Bold = true;
                    worksheet[count]["A1:V1"].ColumnWidth = 300;
                    worksheet[count]["A1:V1"].Style.NumberFormat = "0.00";
                  
                     worksheet[count].Import(table, true, 0, 0);
                    count  ;

               }

                byte[] docBytes = workbook.SaveDocument(DocumentFormat.Xlsx);

                return File(docBytes, "application/vnd.ms-excel", $"ExportForecastReport_{DateTime.Now.ToString("HH-mm-ss yyyyy-dd-MM")}.xlsx"); // returns a FileStreamResult 
}

error thrown while trying to generate second worksheet:{"Worksheet index should be positive and less than the number of worksheets. (Parameter 'index')"}

CodePudding user response:

You should be able to do so with the following:

var newWorksheet = (Excel.Worksheet)this.Application.Worksheets.Add();

The idea is that you first add a new, empty Worksheet to the workbook and then work on it (similarly to what you would do manually in Excel)

CodePudding user response:

You can use EPPlus Nuget package in your project, Then use below code.

public IActionResult EveryExcel([FromForm] Student users)
    {
        var stream = new MemoryStream();
        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
        using (var xlPackage = new ExcelPackage(stream)) 
        {
            int i  = 1;
            foreach(var user in users)
            {
                var worksheet = xlPackage.Workbook.Worksheets.Add($"StudentAll{i}");
                var namedStyle = xlPackage.Workbook.Styles.CreateNamedStyle($"HyperLink{i}");
                namedStyle.Style.Font.UnderLine = true;
                namedStyle.Style.Font.Color.SetColor(Color.Blue);
                const int startRow = 5;
                var row = startRow;

                worksheet.Cells["A1"].Value = "Sample";
                using (var r = worksheet.Cells["A1:C1"])
                {
                    r.Merge = true;
                    r.Style.Font.Color.SetColor(Color.White);
                    r.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.CenterContinuous;
                    r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    r.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(23, 55, 93));
                }

                worksheet.Cells["A4"].Value = "ID";
                worksheet.Cells["B4"].Value = "Name";
                worksheet.Cells["C4"].Value = "Surname";
                worksheet.Cells["A4:C4"].Style.Fill.PatternType = ExcelFillStyle.Solid;
                worksheet.Cells["A4:C4"].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(184, 204, 228));
                worksheet.Cells["A4:C4"].Style.Font.Bold = true;

                worksheet.Cells[row, 1].Value = user.Id;
                worksheet.Cells[row, 2].Value = user.Name;
                worksheet.Cells[row, 3].Value = user.Surname;

                i  ;
            }              
            xlPackage.Save();
        }
        stream.Position = 0;
        return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "students.xlsx");
    }

Then it will generate a new sheet for every student

enter image description here

  • Related