C# COM interact with Excel via Com Microsoft.Office.Interop.Excel,write content to sheet cell

1.Add Com Reference,Microsoft.Office.Interop.Excel

 

 

2.

using Microsoft.Office.Interop.Excel;
using System;
using System.IO;
using System.Runtime.CompilerServices;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace ConsoleApp56
{
    internal class Program
    {
        static Excel.Application excelApp;
        string path = System.IO.Directory.GetCurrentDirectory();
        static List<Book> booksList { get; set; }
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
            InitBooksList();
            ExcelDemo();
        }

        private static void InitBooksList()
        {
            booksList = new List<Book>();
            for(int i=0;i<1000;i++)
            {
                booksList.Add(new Book()
                {
                    Id=i,
                    Author=$"Author_{i}",
                    ISBN=$"ISBN_{i}",
                    Name=$"Name_{i}",
                    Summary=$"Summary_{i}",
                    Title=$"Title_{i}",
                    Topic=$"Topic_{i}"
                });
            }
        }

        private static void ExcelDemo()
        {
            excelApp=new Excel.Application();
            Workbook book = excelApp.Workbooks.Add(XlSheetType.xlWorksheet);
            if(book!=null)
            {
                var sheet = book.ActiveSheet;
                if(sheet!=null)
                {
                    if(booksList!=null && booksList.Count()>0)
                    {
                        var props = typeof(Book).GetProperties();
                        var propsCount = props.Count();
                        int rowCount = booksList.Count;
                        for(int i=0;i<rowCount;i++)
                        {
                            for(int j=0;j<propsCount;j++)
                            {
                                var strValue = props[j].GetValue(booksList[i])?.ToString();
                                sheet.Cells[i+1, j + 1] = strValue;
                            }
                        }
                    } 
                    string fileName = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), $"Excel_{DateTime.Now.ToString("yyyyMMddHHmmffff")}.xlsx");
                    book.SaveAs2(fileName);
                    Console.WriteLine(fileName);
                }
            }
            Console.WriteLine("Finished");
        }
    }


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

 

posted @ 2024-08-27 16:27  FredGrit  阅读(4)  评论(0编辑  收藏  举报