EXPORT
runs a C# function which has an SQL Query and exports the data to an excel file and saves on the local machine. Once the action of saving is completed it should return to page called admin and for some reasons it is not doing so and returning to an empty page我在控制器中具有以下代码
[Authorize(Roles = "Admin")]
public ActionResult ExportWBData()
{
sqlcon.Open();
string strGetAllWBData = @"select Product, Term, BidVolume, BidCP as BidCounterParty, Bid, Offer, OfferCP as OfferCounterParty, OfferVolume from CanadianCrudes";
SqlCommand cmdGetAllWBData = new SqlCommand(strGetAllWBData, sqlcon);
DataTable dtGetAllWBData = new DataTable();
SqlDataAdapter daGetAllWBData = new SqlDataAdapter();
daGetAllWBData.SelectCommand = cmdGetAllWBData;
daGetAllWBData.Fill(dtGetAllWBData);
sqlcon.Close();
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets["Sheet1"];
worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.ActiveSheet;
for (int i = 0; i < dtGetAllWBData.Rows.Count; i++)
{
for (int j = 0; j < dtGetAllWBData.Columns.Count; j++)
{
worksheet.Cells[1, j + 1] = dtGetAllWBData.Columns[j].ToString();
worksheet.Cells[i + 2, j + 1] = dtGetAllWBData.Rows[i][j].ToString();
}
}
string fromFormat = "dd/MM/yyyy";
string toFormat = "MM-dd-yyyy";
DateTime newDate = DateTime.ParseExact(DateTime.Today.ToString(fromFormat), fromFormat, null);
string filedate = newDate.ToString(toFormat);
workbook.SaveAs(@"Z:\WBDomesticDumps\WBData " + filedate + ".xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(true, Type.Missing, Type.Missing);
app.Quit();
return Admin();
}
layout页面是
<li>@Html.ActionLink("Export", "ExportWBData", "Home")</li>
可能我知道一种更好的方法吗?
IMO最简单的方法是创建一个写入数据表的视图。如果然后将内容类型标头设置为
The plus side of this is that you can use regular View templating (razor or otherwise) to manage your view logic and your controller logic winds up being a lot cleaner.
simple修复 更换
return Admin()
与
return RedirectToAction("Admin","Home");
您的Excel功能看起来不错。我相信问题是您的回报。
应该更像这样:
return RedirectToAction("Admin");