SQL Server 使用openxml从数据库生成excel工作表

5jvtdoz2  于 2023-01-08  发布在  其他
关注(0)|答案(2)|浏览(146)

我需要从数据库使用linq生成多个选项卡或工作表excel表。如何动态地做。我的意思是有没有办法从数据库动态设置列标题名称。我使用asp.net核心。需要从数据库表动态生成列名称和长度。

svdrlsy4

svdrlsy41#

请确保您已经安装了DocumentFormat.OpenXml包。您可以参考here
下面是一个简单的演示:
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.结果:

ubbxdtey

ubbxdtey2#

我用C#找到了这个例子。也许它能给你指明正确的方向。
Export DataTable to Excel with Open Xml SDK in c#

相关问题