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; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现