C# export List<T> as table in word file by OpenXML

install-package DocumentFormat.OpenXml;

 

 

//c#
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Diagnostics;
using System.Reflection; 

namespace ConsoleApp24
{
    internal class Program
    {
        static List<Book> booksList;
        static void Main(string[] args)
        {
            ExportDemo();
        }

        static void ExportDemo()
        {
            string fileName = $"Word_{DateTime.Now:yyyyMMddHHmmssffff}.docx";
            InitBooksList();
            ExportListTToWordTable<Book>(booksList, fileName);

            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = "winword.exe",
                Arguments = $"\"{fileName}\"",
                Verb = "runas",
                UseShellExecute = true
            };

            Process.Start(startInfo);
            Console.WriteLine($"Generated document file {fileName}!");
        }

        static void ExportListTToWordTable<T>(List<T> dataList, string wordFile)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Create(wordFile,
                WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = doc.AddMainDocumentPart();
                mainPart.Document = new Document();
                Body body = new Body();

                // Section Properties
                SectionProperties sectionProps = new SectionProperties(
                    new PageSize() { Width = 16838, Height = 11906, Orient = PageOrientationValues.Landscape },
                    new PageMargin() { Top = 720, Right = 720, Bottom = 720, Left = 720 }
                );

                // Table
                Table table = new Table();
                TableProperties tblProps = new TableProperties(
                    new TableBorders(
                        new TopBorder { Val = BorderValues.Single, Size = 6 },
                        new BottomBorder { Val = BorderValues.Single, Size = 6 },
                        new LeftBorder { Val = BorderValues.Single, Size = 6 },
                        new RightBorder { Val = BorderValues.Single, Size = 6 },
                        new InsideHorizontalBorder { Val = BorderValues.Single, Size = 6 },
                        new InsideVerticalBorder { Val = BorderValues.Single, Size = 6 }
                    )
                );
                table.AppendChild(tblProps);

                var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

                // Header
                TableRow headerRow = new TableRow();
                foreach (var prop in props)
                    headerRow.Append(CreateTableCell(prop.Name, "40", true));
                table.Append(headerRow);

                // Rows
                foreach (var item in dataList)
                {
                    TableRow row = new TableRow();
                    foreach (var prop in props)
                    {
                        var value = prop.GetValue(item)?.ToString() ?? string.Empty;
                        row.Append(CreateTableCell(value, "20"));
                    }
                    table.Append(row);
                }

                body.Append(table);

                // Append Section Properties
                body.Append(new Paragraph(new Run(new Text("")))
                {
                    ParagraphProperties = new ParagraphProperties(sectionProps)
                });                

                mainPart.Document.Append(body);
                mainPart.Document.Save();
            }
        }

        static TableCell CreateTableCell(string text, string fontSize, bool isBold = false)
        {
            TableCell cell = new TableCell();
            TableCellProperties cellProperties = new TableCellProperties(
                new TableCellWidth() { Type = TableWidthUnitValues.Auto }
            );
            cell.AppendChild(cellProperties);

            Paragraph paragraph = new Paragraph();
            Run run = new Run();
            RunProperties runProperties = new RunProperties
            {
                FontSize = new FontSize() { Val = fontSize }
            };
            if (isBold)
                runProperties.Append(new Bold());

            run.RunProperties = runProperties;
            run.Append(new Text(text));
            paragraph.Append(run);
            cell.Append(paragraph);

            return cell;
        }

        
        static void InitBooksList()
        {
            booksList = new List<Book>();
            for (int i = 1; i <= 10000; i++)
            {
                booksList.Add(new Book()
                {
                    Id = i,
                    Name = $"Name_{i}",
                    Author = $"Author_{i}",
                    Description = $"Description_{i}",
                    Title = $"Title_{i}",
                    Topic = $"Topic_{i}",
                    Summary = $"Summary_{i}",
                    Chapter = $"Chapter_{i}",
                    ISBN = $"ISBN_{i}_{Guid.NewGuid():N}"
                });
            }
        }
    }

    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public string Description { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
        public string Summary { get; set; }
        public string Chapter { get; set; }
        public string ISBN { get; set; }
    }
}
 

 

 

 

image

 

 

 

image

 

posted @ 2025-09-02 19:23  FredGrit  阅读(9)  评论(0)    收藏  举报