[ASP.net] 取得Excel檔的Sheet名稱
使用前請先注意Server環境要先設定好
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//引用Microsoft Excel相關參考
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
//移機時記得Bin底下的Microsoft.Office.Interop.Excel.dll和office.dll等,Excel相關dll也要Copy過去
public partial class myTest : System.Web.UI.Page
{
/*** Excel Interop reference ***/
Microsoft.Office.Interop.Excel.Application xlApp = null;
Workbook wb = null;
Worksheet ws = null;
Range aRange = null;
//*******************************/
/// <summary>
/// 取得該Excel檔的第一個SheetName
/// </summary>
/// <param name="excel_filePath">Excel檔在Server上的實體路徑</param>
/// <returns>回傳 Excel檔的第一個SheetName</returns>
protected String Get_SheetName(string excel_filePath)
{
try
{
if (this.xlApp == null)
{
this.xlApp = new Microsoft.Office.Interop.Excel.Application();
}
//打開Server上的Excel檔案
this.xlApp.Workbooks.Open(excel_filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
this.wb = this.xlApp.Workbooks[1];//第一個Workbook
this.wb.Save();
this.ws = (Worksheet)this.wb.Worksheets[1];
return this.ws.Name;
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{//就算return,finally區塊還是會執行,除非下關閉程式,關閉電源的指令
if (this.xlApp != null)
{
this.xlApp.Workbooks.Close();
this.xlApp.Quit();
try
{
//刪除 Windows工作管理員中的Excel.exe 處理緒.
System.Runtime.InteropServices.Marshal.ReleaseComObject(this.xlApp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(this.ws);
System.Runtime.InteropServices.Marshal.ReleaseComObject(this.aRange);
}
catch { }
this.xlApp = null;
this.wb = null;
this.ws = null;
this.aRange = null;
}//End if (this.xlApp != null)
}
}
}
※2011.12.27 追記:使用NPOI讀取Excel的SheetName by 亂馬客
論壇討論:c# Excel 如何判斷表單名稱是否已經存在