关于 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 }
4. 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,测试通过