新建并保存一个空的Excel

时间:2023-03-10 01:26:57
新建并保存一个空的Excel

测试用的

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Application = Microsoft.Office.Interop.Excel.Application;
using Microsoft.Office.Interop.Excel;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices; namespace ExcelTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string fileName;
Workbook workbook;
object missing = Missing.Value;
Application app; private void button1_Click(object sender, EventArgs e)
{
try
{
app = new Application()
{
Visible = false
};
workbook = app.Workbooks.Add();
fileName = System.Windows.Forms.Application.StartupPath + "\\excel.xlsx";
SaveAsFile();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
} public void SaveAsFile()
{
if (string.IsNullOrEmpty(fileName))
{
throw new Exception("没有指定输出文件路径!");
} XlFileFormat fileFormat;
if (String.Compare(Path.GetExtension(fileName).ToLower(), ".xlsx", false) == )
{
fileFormat = XlFileFormat.xlWorkbookDefault; //Excel 2007版本
}
else
{
fileFormat = XlFileFormat.xlAddIn8;//Excel 2003版本
} try
{
//workbook.Save();
workbook.SaveAs(fileName, fileFormat, missing, missing, missing, missing, XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
}
catch (Exception ex)
{
// ExceptionLog.Instance.WriteLog(ex, LogType.UI);
throw;
}
finally
{
Dispose();
}
} private void Dispose()
{
int appHwnd = ;
try
{
if (workbook != null)
{
workbook.Close(true, missing, missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
}
if (app != null)
{
appHwnd = app.Hwnd;
app.Workbooks.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
}
}
catch (Exception ex)
{
//ExceptionLog.Instance.WriteLog(ex, LogType.UI);
throw ex;
}
GC.Collect();
if (appHwnd > )
{
KillExcelProcess(appHwnd);
}
} [DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
private static void KillExcelProcess(int appHwnd)
{
Process[] ps = Process.GetProcesses();
IntPtr t = new IntPtr(appHwnd); //得到这个句柄,具体作用是得到这块内存入口
int ExcelID = ;
GetWindowThreadProcessId(t, out ExcelID); //得到本进程唯一标志
foreach (Process p in ps)
{
if (p.ProcessName.ToLower().Equals("excel"))
{
if (p.Id == ExcelID)
{
p.Kill();
}
}
}
}
}
}