C#创建excel并释放资源
2024-09-08 01:12:49
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[] as Worksheet;
} public void Write()
{
ws.Cells[, ] = "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();
}
}
最新文章
- Java中Comparable与Comparator的区别
- linux的whoami, who指令
- Linux Buffer I/O error on device dm-4, logical block
- Ubuntu下安装php7后无法启动Apache
- scala言语基础学习十二
- HDU 4627 The Unsolvable Problem 2013 Multi-University Training Contest 3
- Struts1与Struts2的异同
- 定制ckeditor的菜单
- Android开发——diglog cancel与dismiss方法区别
- 利用JAVA多线程来提高数据处理效率
- mysql时间比较
- dockerfile语法规则
- (转)Spring Boot (十九):使用 Spring Boot Actuator 监控应用
- Safecracker-HDU1015
- 一行一行读Java源码——LinkedBlockingQueue
- myeclipse解决Fail to create the java Virtual Machine
- MediaPlayer音乐播放器、上一首、下一首、播放、停止、自动下一首、进度条
- 【MAVEN】Missing artifact jdk.tools:jdk.tools:jar:1.6 eclipse
- Flink的keyby延时源码
- 从Java开发者的视角解释JavaScript
热门文章
- javaSE基础(二)
- Python Flask Web 框架入门
- 2-3 Vue实例中的数据,事件和方法
- CodeForces 632C Grandma Laura and Apples (模拟)
- bzoj 3733: [Pa2013]Iloczyn【dfs】
- bzoj 1754: [Usaco2005 qua]Bull Math【高精乘法】
- js 本地存储 localStorage 之 angular
- (分治)51NOD 1019 逆序数
- vue-router+webpack线上部署时单页项目路由,刷新页面出现404问题
- hdu6195 cable cable cable