在ASP.NET中使用Excel提供的类读取excel数据

     在ASP.NET中使用Excel类读取Excel文件数据时,会碰到一些奇怪问题,例如“无法读取”等,一般是由于ASP.NET帐户没有操作Excel的权限等原因造成的。解决方法如下:


    运行dcomcnfg(DCOM Config), 在列表中选择Microsoft Excel应用程序,查看属性,身份验证级别选"无",身份标识选"交互式用户",安全性页面,启动和访问均给everyone。(选择安全性选项,编辑可以启动应用程序的用户和更改应用程序配置的用户,在用户中添加ASP.NEt帐户。然后重新启动计算机)(必须,否则仍然无法使用Excel类)。


    做如上配置以后,即可以使用如下方法把Excel中的数据读取到一个DataSet中:

public static DataSet ReadExcel2DataSet(string filePath)
{

   //新建Excel应用程序对象,用于操作Excel 
   Excel.Application app = new Excel.ApplicationClass();

   try
   {   

       //打开Excel文件 
       app.Workbooks.Open  (filePath,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,Missing.Value);

    DataSet ds = new DataSet();
    for(int i=1; i<=app.Worksheets.Count; i++)
    {
       Excel.Worksheet worksheet = app.Worksheets[i] as Excel.Worksheet;
       Excel.Range rngUsed = worksheet.UsedRange;

       DataTable dt = new DataTable();
       ds.Tables.Add(dt);
       for(int j=0; j<rngUsed.Columns.Count; j++)
       {
         dt.Columns.Add();
       }
         
       object[,] table = ((Excel.Range)rngUsed.Rows).Value2 as object[,];
       if(table == null)
       {
          continue;
       }

       for(int m=1; m<=table.GetLength(0); m++)
       {
         DataRow dr = dt.NewRow();
         dt.Rows.Add(dr);      
         for(int n=1; n<=dt.Columns.Count; n++)
         {
           dr[n-1] = table.GetValue(m,n);
         }
       }
    }

    app.Workbooks[1].Close(Missing.Value,Missing.Value,Missing.Value);    
    return ds;
   }
   catch
   {    
     throw;    
   }
   finally
   {
     app.Quit();
   }
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值