我正在开发一个功能“将数据从 sql server 数据库导出到 MVC3 中的 Excel”,我想根据某些条件选择数据,然后将所选数据导出到 Excel。现在我实现了如下功能,比如说截图中,如果我选择“本月到期”然后提交,在excel中只会显示本月到期的会员,而不是所有会员。如果我在日历中选择两个日期,它只显示在两个选定日期之间到期的成员。另外,我可以根据sql语句将数据从数据库导出到excel。问题是我可以编写将数据库中的所有数据导出到excel的sql语句,而不是基于条件(本周到期,本月到期......)。我发布我的代码。有任何想法吗?非常感谢。
更新日期控制器
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>