我有一个Asp.Net MVC Web应用程序,其中一个网页链接EXPORT
运行C#函数,该函数具有SQL查询并将数据导出到excel文件并保存在本地计算机上。一旦保存操作完成,它应该返回到名为admin的页面,由于某些原因它没有这样做并返回到空页
我在控制器中有以下代码
[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();
}
布局页面是
<li>@Html.ActionLink("Export", "ExportWBData", "Home")</li>
我可以知道更好的方法吗?
答案 0 :(得分:2)
执行此操作的最简单方法imo是创建一个编写数据HTML表的视图。如果您然后将内容类型标题设置为application/vnd.ms-excel
,那么大多数浏览器会将其识别为excel文件并提示您打开或保存。
这方面的优点是你可以使用常规的视图模板(剃须刀或其他)来管理你的视图逻辑,你的控制器逻辑会变得更加清洁。
答案 1 :(得分:0)
简单修复 取代
return Admin()
与
return RedirectToAction("Admin","Home");
答案 2 :(得分:0)
您的Excel功能看起来很好。我相信问题在于你的回归。
应该更像这样:
return RedirectToAction("Admin");