1. 项目中添加引用“Microsoft.Office.Interop.Excel”;
2. 添加 Using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Excel;
namespace MSAD.Common.OfficeUtility
{
/// <summary>
/// Workbook related
/// </summary>
public class ExcelWorkbookUtil:IDisposable
{
/// <summary>
/// Create or open an excel file
/// If the file exists, will open the file
/// If the file doesn't exist, will create a new excel file
/// </summary>
/// <param name="excelApp">The current excel application</param>
/// <param name="path">The excel file path</param>
/// <returns>Workbook with full path</returns>
public static Workbook CreateOrOpenExcelFile(ExcelApp excelApp, string path)
{
Workbook curWorkbook = null;
path = Path.GetFullPath(path);
try
{
if (File.Exists(path))
{
curWorkbook = excelApp.ExcelAppInstance.Workbooks.Open(path, 0, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
return curWorkbook;
}
curWorkbook = excelApp.ExcelAppInstance.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
}
curWorkbook.SaveAs(path, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
catch (Exception ex)
{
throw new Exception(string.Format("There's error when openning/ creating excel file {0}. Exception message: {1}", path, ex.Message));
}
return curWorkbook;
}
public static void Save(Workbook workbook)
{
workbook.Save();
}
/// <summary>
/// Save worrkook as
/// </summary>
/// <param name="workbook"></param>
/// <param name="fileFormat">Details can be seen http://msdn.microsoft.com/zh-cn/library/microsoft.office.interop.excel.XlFileFormat.aspx</param>
/// <param name="fullPath">Full file path</param>
public static void SaveAs(Workbook workbook, XlFileFormat fileFormat, string fullPath)
{
workbook.SaveAs(fullPath, fileFormat, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, XlSaveAsAccessMode.xlExclusive, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
}
public static void Save(Workbook workbook, string filePath)
{
workbook.SaveCopyAs(filePath);
}
public static void SaveCopy(Workbook workbook, string filePath)
{
workbook.SaveCopyAs(filePath);
}
#region IDisposable Members
public void Dispose()
{
}
#endregion
}
}