標籤:style blog color io os ar for sp 檔案
using System;using Microsoft.Office.Interop.Excel;using Excel = Microsoft.Office.Interop.Excel;using System.IO;using System.Windows.Forms;using System.Runtime.InteropServices;public class Class2 { private string filePath; private Excel.Application app = null; private Workbook wb; private Worksheet ws; private Workbooks wbs; /// <summary> /// 建立 /// </summary> /// <param name="filePath"></param> public void create(string filePath) { this.filePath = filePath; app = new Excel.Application(); if (app == null) { Out.show("無法建立Excel對象,可能您的電腦未安裝Excel!"); app.Quit(); GC.Collect(); return; } try { app.Visible = false; app.Application.DisplayAlerts = false; } catch (Exception e) { } wbs = app.Workbooks; wb = wbs.Add(Excel.XlWBATemplate.xlWBATWorksheet); ws = wb.Worksheets[1] as Worksheet; } public void Write() { ws.Cells[1, 1] = "hello"; } /// <summary> /// 儲存檔案 /// </summary> public void Save() { while (File.Exists(filePath)) { try { File.Delete(filePath); break; } catch (Exception e) { if (MessageBox.Show("該檔案已被佔用,請關閉", "提示", MessageBoxButtons.RetryCancel) != DialogResult.Retry) { break; }; } } wb.Saved = true; wb.SaveAs(filePath); Kill(); } [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID); /// <summary> /// 殺掉對應進程,釋放資源 /// </summary> public void Kill() { int processId; GetWindowThreadProcessId(new IntPtr(app.Hwnd), out processId); Out.show(processId.ToString()); System.Diagnostics.Process.GetProcessById(processId).Kill(); } }
C#建立excel並釋放資源