我使用ExcelLibrary并保存excel文件后我想通过WebClient下载它,我设置完全控制文件夹,但我看到拒绝访问。
我的代码是:
public class GenerateExcelClass
{
System.Data.DataTable dtCustmer = new System.Data.DataTable();
object[] query;
public void CreateExcelClass<T>(T[] listObj, string fileName, string sheetName = "sheet")
{
string generatefileName = fileName + HttpContext.Current.Request.Cookies["ImenBourse"]["userId"];
dtCustmer = ConvertToDatatable(listObj);
DataSet ds = new DataSet("New_DataSet");
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
ds.Tables.Add(dtCustmer);
string newFilePath = HttpContext.Current.Server.MapPath(generatefileName + ".xls");
ExcelLibrary.DataSetHelper.CreateWorkbook(newFilePath, ds);
WebClient webClient = new WebClient();
var path = HttpContext.Current.Server.MapPath("");
webClient.DownloadFile(path, generatefileName + ".xls");
}
public static DataTable ConvertToDatatable<T>(T[] list)
{
PropertyInfo[] properties = list.GetType().GetElementType().GetProperties();
DataTable dt = CreateDataTable(properties);
if (list.Length != 0)
{
foreach (object o in list)
FillData(properties, dt, o);
}
return dt;
}
private static DataTable CreateDataTable(PropertyInfo[] properties)
{
DataTable dt = new DataTable();
DataColumn dc = null;
foreach (PropertyInfo pi in properties)
{
DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(pi, typeof(DisplayNameAttribute));
dt.Columns.Add(attr.DisplayName, pi.PropertyType);
}
return dt;
}
private static void FillData(PropertyInfo[] properties, DataTable dt, Object o)
{
DataRow dr = dt.NewRow();
foreach (PropertyInfo pi in properties)
{
DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(pi, typeof(DisplayNameAttribute));
if (dt.Columns.Contains(attr.DisplayName))
{
dr[attr.DisplayName] = pi.GetValue(o, null);
}
}
dt.Rows.Add(dr);
}
}
答案 0 :(得分:0)
请尝试新方法...而不是公开 真实 文件,然后公开服务器文件系统,将excel文件发送到具有正确mime类型的客户端浏览器
创建文件后,如果您需要或随时使用内存流并在响应
中将其保存到磁盘文件中指定正确的 Response.ContentType =“application / vnd.ms-excel”并将其写入。