關於 IIS 上 Excel 文件的訪問, 一路上困難重重, 最后按以下步驟進行設置, 可在 IIS 中正常使用!
1. 引用及代碼:
1). 項目中添加 Excel 程序集引用(注意: 從系統 COM 組件中選擇"Microsoft Excel 1*.0 Object Library"):
2). 設置 Excel 程序集屬性: 選擇已添加的 Excel 程序集 Microsoft.Office.Interop.Excel, 右鍵選擇屬性, Copy Local 改為 True, Embed Interop Types 改為 False.
3). Excel 訪問代碼:
1 private ICollection<Sample> ReadExcel(string fileName) 2 { 3 Application excel = new ApplicationClass { Visible = false, DisplayAlerts = false }; 4 Workbook workbook = null; 5 Worksheet sheet = null; 6 7 try 8 { 9 workbook = excel.Workbooks.Open(fileName); 10 sheet = (Worksheet)workbook.ActiveSheet; 11 12 if (sheet == null) 13 { 14 throw new Exception("Read excel file failed!"); 15 } 16 17 Range range = null; 18 int rowIndex = 1; 19 20 ICollection<Sample> list = new HashSet<Sample>(); 21 for (rowIndex = 2; rowIndex <= sheet.UsedRange.Rows.Count; rowIndex++) 22 { 23 if (!this.HasValue(sheet, rowIndex)) 24 { 25 break; 26 } 27 28 int colIndex = 1; 29 var sample = new Sample(); 30 range = (Range)sheet.Cells[rowIndex, colIndex++]; 31 sample.Name = range.Value;
// ... other code logic 32 list.Add(sample); 33 } 34 return list; 35 } 36 catch (Exception ex) 37 { 38 throw ex.GetInnerException(); 39 } 40 finally 41 { 42 if (workbook != null) 43 { 44 workbook.Close(false); 45 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); 46 System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); 47 } 48 workbook = null; 49 excel.Workbooks.Close(); 50 excel.Quit(); 51 System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); 52 excel = null; 53 GC.Collect(); 54 GC.WaitForPendingFinalizers(); 55 File.Delete(fileName); 56 } 57 }
2. IIS 設置:
1). 站點發布后, 選擇 Authentication -> Anonymous Authentication -> Edit 選擇 Application pool identity -> OK.
2). IIS Application pool 選中當前 Application -> Advanced Settings -> Identity 選擇 Network Service -> OK
3. COM 組建設置:
1).開始--〉運行--〉cmd
2)命令提示符下面,輸入mmc -32,打開32的控制台
3).文件菜單中或根節點右鍵,添加刪除管理單元--〉組件服務
4).在"DCOM配置"中找到"Microsoft Excel Application",在它上面點擊右鍵,然后點擊"屬性",彈出"Microsoft Excel Application 屬性"對話框
5).點擊"標識(Identity)"標簽,選擇"交互式用戶(The interactive user)"
6).點擊"安全(Security)"標簽,在"啟動和激活權限(Launch and Activition Perimissions)"上點擊"自定義(Customize)",然后點擊對應的"編輯(Edit)"按鈕,在彈出的"安全性(Security)"對話框中填加一個"NETWORK SERVICE"用戶(注意要選擇本計算機名),並給它賦予"本地啟動"和"本地激活"權限
7).依然是"安全(Security)"標簽,在"訪問權限(Access Perimissions)"上點擊"自定義(Customize)",然后點擊"編輯(Edit)",在彈出的"安全性"對話框中也填加一個"NETWORK SERVICE"用戶,然后賦予"本地訪問"權限.



4.重新啟動IIS,測試通過