如何在C#中写Excel文件
1. 创建一个Console Application, 添加COM选显卡中的Microsoft Excel 12.0 Object Library引用.
2. 粘贴下面的源代码.
using System; using Excel = Microsoft.Office.Interop.Excel; namespace CShartExcelTest { class Program { static void Main(string[] args) { try { string[,] values = { {"Tom", "18", "Beijing", "13912345678"}, {"Jerry", "17", "Shanghai", "13687654321"} }; Excel.Application objApp; Excel._Workbook objBook; Excel.Workbooks objBooks; Excel.Sheets objSheets; Excel._Worksheet objSheet; Excel.Range range; // Instantiate Excel and start a new workbook. objApp = new Excel.Application(); objBooks = objApp.Workbooks; objBook = objBooks.Add(System.Reflection.Missing.Value); objSheets = objBook.Worksheets; objSheet = (Excel._Worksheet)objSheets.get_Item(1); //Get the range where the starting cell has the address range = objSheet.get_Range("A2", System.Reflection.Missing.Value); range = range.get_Resize(2, 4); range.set_Value(System.Reflection.Missing.Value, values); //Construct the header. objSheet.Cells[1, 1] = "Name"; objSheet.Cells[1, 2] = "Age"; objSheet.Cells[1, 3] = "HomeTown"; objSheet.Cells[1, 4] = "Mobile"; bool bSave = false; if (bSave) { //Return control of Excel to the user. objApp.Visible = true; objApp.UserControl = true; } else { objBook.SaveAs(@"c:\temp\csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value); objBook.Close(true, System.Reflection.Missing.Value, System.Reflection.Missing.Value); objApp.Quit(); releaseObject(objSheet); releaseObject(objBook); releaseObject(objApp); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } private static void releaseObject(object obj) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } catch (Exception ex) { obj = null; Console.WriteLine("Exception Occured while releasing object " + ex.ToString()); } finally { GC.Collect(); } } } }
参考资料:
How to create Excel file in C#
http://csharp.net-informations.com/excel/csharp-create-excel.htm
How to automate Excel by using Visual C# to fill or to obtain data in a range by using arrays
http://support.microsoft.com/kb/302096
How to automate Microsoft Excel from Microsoft Visual C# .NET
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律