C#-生成Excel文件
引入命名空间:
1 2 | using Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; |
创建Sheet:
var app = new Microsoft.Office.Interop.Excel.Application(); Workbook wb = app.Workbooks.Add(System.Reflection.Missing.Value); Worksheet ws = wb.Sheets[1];
设置格式:
Range allRange = ws.Range[ws.Cells[1, 1], ws.Cells[5, 5]]; Range titleRange = ws.Range[ws.Cells[1, 1], ws.Cells[1, 5]]; Range mainRange = ws.Range[ws.Cells[1, 2], ws.Cells[5, 2]]; allRange.Font.Name = "Times New Roman"; allRange.WrapText = false; titleRange.Font.Bold = true; titleRange.Font.Size = 15; titleRange.EntireColumn.AutoFit(); titleRange.Borders.LineStyle = XlLineStyle.xlContinuous; titleRange.Interior.ColorIndex = ExcelColor.green; mainRange.Interior.ColorIndex = ExcelColor.cyan;
填充内容:
ws.Cells[1, 1] = "ID"; ws.Cells[1, 2] = "Name"; ws.Cells[1, 3] = "Age"; ws.Cells[1, 4] = "Number"; ws.Cells[1, 5] = "Address"; for (int j = 1; j < 5; j++) { ws.Cells[1 + j, 1] = j; ws.Cells[1 + j, 2] = "名称" + j; ws.Cells[1 + j, 3] = 20 + j; ws.Cells[1 + j, 4] = 123450 + j; ws.Cells[1 + j, 5] = "地址" + j; }
保存到文件,释放进程:
ws.SaveAs(file, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing); wb.Close(false, Type.Missing, Type.Missing); wb = null; app.Quit(); GC.Collect(); KeyProcess.Kill(app);
ColorIndex:
class ExcelColor { public const int transparent = 0; public const int black = 1; public const int white = 2; public const int red = 3; public const int green = 4; public const int blue = 33; public const int yellow = 6; public const int pink = 7; public const int cyan = 8; public const int darkRed = 9; public const int dark = 29; public const int gray = 15; public const int darkCyan = 31; public const int darkSlateBlue = 51; }
释放进程函数:
class KeyProcess { [DllImport("User32.dll", CharSet = CharSet.Auto)] static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID); public static void Kill(Microsoft.Office.Interop.Excel.Application excel) { IntPtr add = new IntPtr(excel.Hwnd); int pid = 0; GetWindowThreadProcessId(add, out pid); System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(pid); p.Kill(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)