简体   繁体   English

如何在工作簿中添加多个工作表 C#

[英]How to add multiple worksheets in workbook C#

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.我正在尝试为列表中的每个学生生成多个工作表,但不确定如何实现这一点,我可以使用一个工作表成功生成 Excel 文档,但在一张工作表中显示所有学生,我如何为每个学生生成一个新工作表?我尝试使用下面的代码实现此目的,谢谢。

 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')"}尝试生成第二个工作表时抛出错误:{“工作表索引应为正数且小于工作表数。(参数‘索引’)”}

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)这个想法是,您首先向工作簿添加一个新的空工作表,然后对其进行处理(类似于您在 Excel 中手动执行的操作)

You can use EPPlus Nuget package in your project, Then use below code.您可以在您的项目中使用EPPlus Nuget package,然后使用以下代码。

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然后它将为每个学生生成一个新表

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM