引入命名空间:
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(); } }
标签:const,Missing,C#,Cells,Excel,生成,int,ws,public From: https://www.cnblogs.com/cfsl/p/17047463.html