在ASP.NET中使用Excel提供的类读取excel数据(转)
时间:2010-09-23 来源:邑尘
在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();
}
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/gentle_wolf/archive/2008/11/27/3394452.aspx