3

I need to generate excel sheet with multiple tabs or sheets using linq from database. How to do it dynamically. I mean is there any way to set column header name dynamically from database. I am using asp.net core. Need generate columns name and length dynamically from database table.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Sadiqul
  • 145
  • 1
  • 11
  • 1
    There are dozens of duplicate questions that show how to use eg [Epplus](https://github.com/JanKallman/EPPlus) to create a workbooks with multiple sheets from query result, – Panagiotis Kanavos Oct 31 '19 at 18:11
  • 1
    Does this answer your question? [Creating an Excel file on the fly and have it download/save on the client](https://stackoverflow.com/questions/44345788/creating-an-excel-file-on-the-fly-and-have-it-download-save-on-the-client) – Panagiotis Kanavos Oct 31 '19 at 18:14

2 Answers2

9

Be sure that you have installed DocumentFormat.OpenXml package.You could refer to here.

Here is a simple demo like below:

1.Model:

public class TestModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}

2.Controller:

public class TestModelsController : Controller
{
    private readonly CreateexcelContext _context;

    public TestModelsController(CreateexcelContext context)
    {
        _context = context;
    }

    [Route("/excel")]
    public void WriteExcelFile()
    {
       var persons = _context.TestModel.ToList();
        DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (typeof(DataTable)));
        using (SpreadsheetDocument document = SpreadsheetDocument.Create("TestNewData.xlsx", SpreadsheetDocumentType.Workbook))
        {
            WorkbookPart workbookPart = document.AddWorkbookPart();
            workbookPart.Workbook = new Workbook();

            WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
            var sheetData = new SheetData();
            worksheetPart.Worksheet = new Worksheet(sheetData);

            Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
            Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };

            sheets.Append(sheet);
            Row headerRow = new Row();
            List<String> columns = new List<string>();
            foreach (System.Data.DataColumn column in table.Columns)
            {
                columns.Add(column.ColumnName);
                Cell cell = new Cell();
                cell.DataType = CellValues.String;
                cell.CellValue = new CellValue(column.ColumnName);
                headerRow.AppendChild(cell);
            }

            sheetData.AppendChild(headerRow);
            foreach (DataRow dsrow in table.Rows)
            {
                Row newRow = new Row();
                foreach (String col in columns)
                {
                    Cell cell = new Cell();
                    cell.DataType = CellValues.String;
                    cell.CellValue = new CellValue(dsrow[col].ToString());
                    newRow.AppendChild(cell);
                }

                sheetData.AppendChild(newRow);
            }
            workbookPart.Workbook.Save();
        }
    }
}

3.Result: enter image description here

Rena
  • 30,832
  • 6
  • 37
  • 72
0

I found this example using C#. Maybe it can point you in the right direction.

Export DataTable to Excel with Open Xml SDK in c#

jrdevdba
  • 133
  • 1
  • 4
  • I did read the question. You can also try this page. https://www.aspsnippets.com/Articles/OpenXml-MVC-Example-Export-to-Excel-using-OpenXml-in-ASPNet-MVC.aspx – jrdevdba Oct 31 '19 at 18:13
  • @Sadiqul the link is definitely relevant. The answer's problem is that it *doesn't* really explain what's going on. Link only answers aren't useful. The *question* itself isn't a great one either - there are many duplicate questions that show how to create Excel sheets on the server using Open XML, or a higher level library like EPPlus – Panagiotis Kanavos Oct 31 '19 at 18:15
  • "Link only answers aren't useful" This is true; sorry about that. In this case, it's just that I am not a developer myself but wanted to link to some explanation from which the OP could build out similar logic. I chose to post something rather than nothing, but I guess that is not always helpful. – jrdevdba Oct 31 '19 at 18:53
  • Maybe my answer will help you. Though I highly recommend using SAX approach when dealing with OpenXML, It's much faster and If your query results are big in terms of memory drain you can also minize that to almost nothing. Here is my link: https://stackoverflow.com/questions/55612337/openxml-change-excel-cell-format-date-and-number-when-exporting-from-datagrid – Lucy82 Oct 31 '19 at 21:21