当我在本地计算机上使用此类时,它会提示用户打开xlsx文件,但是当我发布到Azure时,它不再有效。我很确定我的问题是我在Azure上处理文件流时没有。希望有人可以帮助我。
我在本地发布时有效的代码 -
if (vm.ExportClicked != null && vm.ExportClicked.ToLower() == "true")
{
//doing this because I need the entire list not just a single page
CustomerLastOrderListViewModel vm1 = new CustomerLastOrderListViewModel();
var oPagedCustomerLists = oFilteredCustomerList.OrderByDescending(c => c.Id);
//.ToList();
List<CustomerLastOrderViewModel> customersLastOrders = CombineWithLastOrder(oPagedCustomerLists.ToList());
vm1.CustomersLastOrder = customersLastOrders;
DataTable dt = CreateCustomerEmailData(vm1, form);
CreateExcelFile.CreateExcelDocument(dt, "CustomerEmailList.xlsx", HttpContext.ApplicationInstance.Response);
我正在使用此响应,因为我无法使用其他任何内容进行编译。 Excel类在文件流中返回信息,我想知道因为我在Azure上并且没有安装Excel,所以我必须做一些不同的事情。
这是CreateExcelDocument -
public static bool CreateExcelDocument(DataTable dt, string filename, System.Web.HttpResponse Response)
{
try
{
DataSet ds = new DataSet();
ds.Tables.Add(dt);
CreateExcelDocumentAsStream(ds, filename, Response);
ds.Tables.Remove(dt);
return true;
}
catch (Exception ex)
{
Trace.WriteLine("Failed, exception thrown: " + ex.Message);
return false;
}
}
public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response)
{
try
{
System.IO.MemoryStream stream = new System.IO.MemoryStream();
using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true))
{
WriteExcelFile(ds, document);
}
stream.Flush();
stream.Position = 0;
Response.ClearContent();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
// NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have
// manually added System.Web to this project's References.
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.AddHeader("content-disposition", "attachment; filename=" + filename);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
byte[] data1 = new byte[stream.Length];
stream.Read(data1, 0, data1.Length);
stream.Close();
Response.BinaryWrite(data1);
Response.Flush();
Response.End();
return true;
}
catch (Exception ex)
{
Trace.WriteLine("Failed, exception thrown: " + ex.Message);
return false;
}
}
答案 0 :(得分:1)
在CreateExcelDocument
尝试更改此内容;
CreateExcelDocumentAsStream(ds, filename, Response);
要;
CreateExcelDocumentAsStream(ds, filename, Response.OutputStream);
我很确定你在接受HttpResponse
时传递Stream
(或者至少我从方法名称推断它,我找不到任何文档,所以我假设它是专有的。)