C# OpenXml print List<string> in word with random fontsize and color

Install-Package DocumentFormat.OpenXml;
private static void SetRunProperties(RunProperties runProperties,
    int fontSize,
    bool isBold,
    bool isItalic,
    bool isUnderline,
    string fontFamily,
    string color)
{
    runProperties.Append(new FontSize()
    {
        Val=(fontSize*2).ToString()
    });

    if (isBold)
    {
        runProperties.Append(new Bold());
    }

    if (isItalic)
    {
        runProperties.Append(new Italic());
    }

    if (isUnderline)
    {
        runProperties.Append(new Underline()
        {
            Val=UnderlineValues.Single
        });
    }

    runProperties.Append(new RunFonts()
    {
        Ascii=fontFamily,
        HighAnsi=fontFamily
    });
    runProperties.Append(new DocumentFormat.OpenXml.Wordprocessing.Color()
    {
        Val=color
    });
}

 

 

 

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Diagnostics;
using System.Drawing; 


namespace ConsoleApp28
{
    internal class Program
    {
        static Random rnd;
        static List<string> colorsList;
        static void Main(string[] args)
        {
            rnd= new Random();
            string docFile = $"Doc_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.docx";
            List<string> strsList=new List<string>();
            for(int i=0;i<1000;i++)
            {
                strsList.Add($"{i+1}_{Guid.NewGuid().ToString("N")}");
            }
            InitColorsList();
            ExportToWord(strsList, docFile);
            Console.WriteLine($"Saved in P{docFile}");

            var proc = new Process()
            {
                StartInfo=new ProcessStartInfo()
                {
                    FileName=docFile,
                    UseShellExecute=true,
                }
            };
            proc.Start();
        }

        private static void InitColorsList()
        {
            colorsList= new List<string>();
            for(int i=0;i<1000;i++)
            {
                System.Drawing.Color color = System.Drawing.Color.FromArgb(255, rnd.Next(0, 255), rnd.Next(0, 255), rnd.Next(0, 255));
                string hexColorStr = ColorToHexString(color);
                colorsList.Add(hexColorStr);
            }                       
        }

        private static string ColorToHexString(System.Drawing.Color color)
        {
            // Convert to 6-digit hex string (without alpha)
            return $"{color.R:X2}{color.G:X2}{color.B:X2}";
        }

        static void ExportToWord(List<string> strsList,string docFile)
        { 
            using (WordprocessingDocument doc = WordprocessingDocument.Create(docFile, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = doc.AddMainDocumentPart();
                mainPart.Document=new Document();
                mainPart.Document.Append(new Body());
                Body body = mainPart.Document.Body;
                // Add section properties to body
               

                //Paragraph paragraph = new Paragraph();
                //SetParagraphAlignment(paragraph, "center");
                SectionProperties sectionProps = new SectionProperties(
                    new PageSize()
                    {
                        Width=16838,
                        Height=11906,
                        Orient=PageOrientationValues.Landscape
                    },
                    new PageMargin()
                    {
                        Top=720*2,
                        Right=720*2,
                        Bottom=720*2,
                        Left=720*2
                    });

                


                foreach (var str in strsList)
                {
                    Paragraph paragraph = new Paragraph();
                    SetParagraphAlignment(paragraph, "left");

                    int fontSize = rnd.Next(20, 100);
                    string colorStr = colorsList[rnd.Next(0, colorsList.Count)];
                    WriteStringToDoc(paragraph, str, fontSize, colorStr);

                    body.Append(paragraph);
                }

                //body.Append(paragraph);
                body.Append(new Paragraph(new Run(new Text("")))
                {
                    ParagraphProperties = new ParagraphProperties(sectionProps)
                });
                mainPart.Document.Save();
            }
        }

        static void WriteStringToDoc(Paragraph paragraph,string str, int fontSize=20, 
            string color = "000000",bool isBold = false, string alignment = "left",
            string fontFamily = "Arial", bool isItalic = false,
            bool isUnderline = false)
        {
            Run run = new Run();
            RunProperties runProperties = new RunProperties();

            // Set font properties
            SetRunProperties(runProperties, fontSize, isBold, isItalic, isUnderline, fontFamily, color);

            // Add properties to run
            if (runProperties.HasChildren)
            {
                run.RunProperties = runProperties;
            }

            // Add text to run             
            run.Append(new Text(str));
            run.Append(new Break());
            // Add run to paragraph
            paragraph.Append(run);
        }

        private static void SetRunProperties(RunProperties runProperties,
            int fontSize,
            bool isBold,
            bool isItalic,
            bool isUnderline,
            string fontFamily,
            string color)
        {
            runProperties.Append(new FontSize()
            {
                Val=(fontSize*2).ToString()
            });

            if (isBold)
            {
                runProperties.Append(new Bold());
            }

            if (isItalic)
            {
                runProperties.Append(new Italic());
            }

            if (isUnderline)
            {
                runProperties.Append(new Underline()
                {
                    Val=UnderlineValues.Single
                });
            }

            runProperties.Append(new RunFonts()
            {
                Ascii=fontFamily,
                HighAnsi=fontFamily
            });
            runProperties.Append(new DocumentFormat.OpenXml.Wordprocessing.Color()
            {
                Val=color
            });
        }


        private static void SetParagraphAlignment(Paragraph paragraph, string alignment)
        {
            ParagraphProperties paragraphProps = new ParagraphProperties();
            switch (alignment.ToLower())
            {
                case "center":
                    paragraphProps.Append(new Justification()
                    {
                        Val=JustificationValues.Center
                    });
                    break;

                case "right":
                    paragraphProps.Append(new Justification()
                    {
                        Val=JustificationValues.Right
                    });
                    break;

                case "both":
                    paragraphProps.Append(new Justification()
                    {
                        Val=JustificationValues.Both
                    });
                    break;

                default:
                    paragraphProps.Append(new Justification()
                    {
                        Val =JustificationValues.Left
                    });
                    break;
            }
        }
    }
}

 

 

 

 

 

 

 

 

 

 

image

 

 

 

 

 

image

 

 

 

image

 

posted @ 2025-09-03 17:26  FredGrit  阅读(4)  评论(0)    收藏  举报