我正在开发一个功能“将数据从sql server数据库导出到MVC3中的Excel”,我想根据特定条件选择数据,然后将所选数据导出到excel。现在我已经实现了以下功能,例如,在屏幕截图中,如果我选择“将在本月过期”然后提交,它将只显示本月将在excel中过期的成员,而不是所有成员。如果我在日历中选择两个日期,则仅显示在两个选定日期之间过期的成员。另外,我可以根据sql语句将数据从数据库导出到excel。问题是我可以写sql语句将所有数据从数据库导出到excel,而不是基于条件(本周到期,本月到期......)。我发布了我的代码。有任何想法吗?非常感谢。
续订日期控制器
public ActionResult Index()
{
ViewData["BreadCrumbs"] = new List<BreadCrumb> {
new BreadCrumb { Url = UrlMaker.ToDefault(), Title = "Home" },
new BreadCrumb {Url = UrlMaker.ToReportsArea(), Title = "Reports Area"},
new BreadCrumb { Title = "Renewal" } };
List<string> expiryOptions = new List<string>();
expiryOptions.Add("Will expire this month");
expiryOptions.Add("Expire next month");
expiryOptions.Add("Will expire this week");
expiryOptions.Add("Expire next week");
expiryOptions.Add("Have expired");
ViewBag.ExpiryOptions = new SelectList(expiryOptions);
ViewBag.a = 0;
ViewBag.ExpiryDate = string.Empty;
return View();
}
[HttpPost]
public ActionResult Index(string option, DateTime? expireFrom, DateTime? expireTo)
{
ViewData["BreadCrumbs"] = new List<BreadCrumb> {
new BreadCrumb { Url = UrlMaker.ToDefault(), Title = "Home" },
new BreadCrumb {Url = UrlMaker.ToReportsArea(), Title = "Reports Area"},
new BreadCrumb { Title = "Renewal" } };
Session["option"] = option;
List<string> expiryOptions = new List<string>();
expiryOptions.Add("will expire this month");
expiryOptions.Add("expire next month");
expiryOptions.Add("will expire this week");
expiryOptions.Add("expire next week");
expiryOptions.Add("have expired");
ViewBag.ExpiryOptions = new SelectList(expiryOptions);
ViewBag.a = 1;
if (expireFrom != null && expireTo != null)
{
ViewBag.ExpiryDate = (memberRepository.renewalDateQuery((DateTime)expireFrom, (DateTime)expireTo));
}
else
{
ViewBag.ExpiryDate = memberRepository.RenewalQuery(option);
}
return View();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.
ConnectionStrings["ProActiveMembershipDB"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
public ActionResult ExportToExcel()
{
//Get the data from database into datatable
string strQuery = "select MemberType,OrganisationName, Forename, Surname, Email, ExpiryDateofScheme from Members ";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
System.Web.UI.WebControls.GridView GridView1 = new System.Web.UI.WebControls.GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=RenewalMemberList.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[4].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[5].Style.Add("background-color", "green");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#AAE92A");
row.Cells[1].Style.Add("background-color", "#AAE92A");
row.Cells[2].Style.Add("background-color", "#AAE92A");
row.Cells[3].Style.Add("background-color", "#AAE92A");
row.Cells[4].Style.Add("background-color", "#AAE92A");
row.Cells[5].Style.Add("background-color", "#AAE92A");
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return View();
}
}
索引视图
@model IEnumerable<ProActiveMembership.Areas.Members.Models.Member>
@{
ViewBag.Title = "Report: Renewal Reports";
Layout = Layout = "~/Views/Shared/ProActive.cshtml";;
}
<h2 class="PageTitle">
<u>Renewal Report</u></h2>
@using (Html.BeginForm("Index", "RenewalDate", FormMethod.Post, new { id = "form" }))
{
<br />
<p>choose from one of the following options:</p>
<p>
I want to see members that: @Html.DropDownList("option", (SelectList)ViewBag.ExpiryOptions, "choose...", new { id = "ddl" })
</p>
}
@using (Html.BeginForm("Index", "RenewalDate", FormMethod.Post))
{
// below date1 is expirefrom date and date2 is the expireto date
<p>
expire between @Html.TextBox("expireFrom", "", new { id = "date1" }) and @Html.TextBox("expireTo", "", new { id = "date2" })
</p>
<input type="submit" value="submit" />
<br />
}
<div class="scrollable">
<table class="RenewalDateReports">
<tr class="RenewalDateReports">
<th class="RenewalDateReports">
Name
</th>
<th class="RenewalDateReports">
Expiry Date
</th>
<th class="RenewalDateReports">
Membership with
</th>
<th class="RenewalDateReports">
Grade
</th>
<th class="RenewalDateReports">
Action
</th>
</tr>
@foreach (var item in ViewBag.ExpiryDate)
{
<tr>
<td class="RenewalDateReports">
@item.Forename @item.Surname
@item.OrganisationName
</td>
<td class="RenewalDateReports">
@item.ExpiryDateofScheme.ToShortDateString()
</td>
<td class="RenewalDateReports">
@item.MembershipGrade.Organisation.OrganisationName
</td>
<td class="RenewalDateReports">
@item.MembershipGrade.GradeName
</td>
<td class="RenewalDateReports">
@* @Html.ActionLink("Notify", "###", new { id = item.MemberID })*@
@Html.ActionLink("Notify", "Communication", "Member", new { Area = "Members" }, null)
</td>
</tr>
@* @Html.ActionLink("Export to Excel", "ExportToExcel", "RenewalDate")*@
}
</table>
</div>
<br />
@Html.ActionLink("Export to Excel", "ExportToExcel", "RenewalDate")
<br />
<script type="text/javascript">
$(document).ready(function () {
$("#ddl").change(function () {
var form = document.getElementById("form");
form.submit();
});
$(function () {
$("#date1").datepicker({
dateFormat: 'dd/mm/yy',
firstDay: 1,
showOn: "button",
buttonImage: "../../assets/images/calendar.gif",
buttonImageOnly: true
});
});
$(function () {
$("#date2").datepicker({
dateFormat: 'dd/mm/yy',
firstDay: 1,
showOn: "button",
buttonImage: "../../assets/images/calendar.gif",
buttonImageOnly: true
});
});
});
</script>
ExportToExcel查看
@{
ViewBag.Title = "ExportToExcel";
}
<h2>ExportToExcel</h2>
答案 0 :(得分:0)
到目前为止,您尝试将哪些内容导出为excel。有不同的dll可用于与Excel交互“EPPLUS”就是其中之一。您可以在
上找到它的教程http://www.jimmycollins.org/blog/?p=547
您可以通过存储过程或查询使用您的条件检索数据,然后可以将该数据绑定到Excel。
编辑部分: - 用于jquery ajax调用
$('#Exportbtn').click(function () {
var drpdownval= $("#DROPDOWN").val();//This Is your selected value
$.ajax({
cache:false,
type: "POST",
url: "@(Url.Action("ExportProducts", "Order"))",
//Method and controller to which u r going to pass the data
data:"drpdownval=" + drpdownval,
success: function (data) {
//Write your success code here after returning from ajax method
//If you have returned view you can assign view to some div
},
error:function (xhr, ajaxOptions, thrownError){
}
});
});
现在在您的控制器中,您需要编写方法
public ActionResult ExportProducts(string drpdownval)
{
//Your Logic goes here
return View("ViewName","ModelName");
}
//请注意,此调用仅返回给ajax调用。如果没有理解则退出注释
请检查Html.ActionLink的所有重载您应该为某个变量赋值
试试这个
@Html.ActionLink(
"Export To Excel", // linkText
"ExportToExcel", // actionName
"Export", // controllerName
new { // routeValues passes to action
blogPostId = blogPostId,
replyblogPostmodel = Model,
},
null // htmlAttributes
)
发布此参考作为参考使用您的参数。
评论是否还有疑问