2015-11-12 4 views
0

Я хочу экспортировать данные в Excel с помощью LINQ MVC 5. На данный момент он работает и экспортирует все данные, но я хотел бы экспортировать только определенные данные, которые я выбрал путем фильтрации (Index Controller). Вот что у меня есть:Экспорт определенных данных в Excel

Модель:

public class Oplata 
{ 
    public int ID { get; set; } 

    [DataType(DataType.Date)] 
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] 
    [Display(Name="Data")] 
    public DateTime DataOplaty { get; set; } 

    [DisplayFormat(DataFormatString = "{0} km")] 
    [Display(Name = "Przebieg")] 
    public int PrzebiegOplaty { get; set; } 

    [Display(Name = "Rodzaj")] 
    public RodzajOplaty RodzajOplaty { get; set; } 

    [DisplayFormat(DataFormatString = "{0:c}")] 
    [Display(Name = "Kwota")] 
    public int KwotaOplaty { get; set; } 

    [DataType(DataType.MultilineText)] 
    [Display(Name = "Szczegóły")] 
    public string DodatkoweInformacjeOplaty { get; set; } 

    [Display(Name = "Numer rejestracyjny")] 
    public string TablicaRejstracyjna { get; set; } 

    public int PojazdID { get; set; } 

    public virtual Pojazd Pojazd { get; set; } 
} 

public enum RodzajOplaty 
{ 
    Naprawa, Przegląd, Ubezpieczenie, Olej, Inne 
} 

Контроллер:

public ActionResult Index(string oplataTyp, string szukajRej, DateTime? fromDate, DateTime? toDate) 
     { 
      var oplaty = from p in db.Oplaty select p; 

      // Daty 
      var MinDate = (from d in db.Oplaty select d.DataOplaty).Min(); 
      var MaxDate = (from d in db.Oplaty select d.DataOplaty).Max(); 

      if (!fromDate.HasValue) fromDate = MinDate; 
      if (!toDate.HasValue) toDate = DateTime.Today.AddDays(1); 
      if (toDate < fromDate) toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1); 
      ViewBag.fromDate = fromDate; 
      ViewBag.toDate = toDate; 

      oplaty = db.Oplaty.Where(c => c.DataOplaty >= fromDate && c.DataOplaty < toDate); 


      // Filtrowanie danych 
      var TypLista = new List<RodzajOplaty>(); 
      var TypWyszukaj = from d in db.Oplaty orderby d.RodzajOplaty select d.RodzajOplaty; 
      TypLista.AddRange(TypWyszukaj.Distinct()); 
      ViewBag.oplataTyp = new SelectList(TypLista); 

      RodzajOplaty RodzajOplaty; 

      if (Enum.TryParse<RodzajOplaty>(oplataTyp, out RodzajOplaty)) 
      { 
       oplaty = oplaty.Where(x => x.RodzajOplaty == RodzajOplaty); 
      } 

      if (!String.IsNullOrEmpty(szukajRej)) 
      { 
       oplaty = oplaty.Where(s => s.TablicaRejstracyjna.Contains(szukajRej)); 
      } 


      // Zliczanie opłat 
      try 
      { 
       ViewBag.SumowanieOplat = oplaty.Sum(x => x.KwotaOplaty); 
      } 
      catch 
      { 
      } 


      return View(oplaty.ToList()); 
     } 

public ActionResult ExportData() 
     { 
      GridView gv = new GridView(); 
      gv.DataSource = db.Oplaty.ToList(); 
      gv.DataBind(); 
      Response.ClearContent(); 
      Response.Buffer = true; 
      Response.AddHeader("content-disposition", "attachment; filename=Raport.xls"); 
      Response.ContentType = "application/ms-excel"; 
      Response.Charset = ""; 
      StringWriter sw = new StringWriter(); 
      HtmlTextWriter htw = new HtmlTextWriter(sw); 
      gv.RenderControl(htw); 
      Response.Output.Write(sw.ToString()); 
      Response.Flush(); 
      Response.End(); 

      return RedirectToAction("Index"); 
     } 

Вид:

@model IEnumerable<AutoMonit.Models.Oplata> 

<h2>Zestawienie opłat pojazdów</h2> 
@Scripts.Render("~/bundles/jqueryui") 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $(".DatePicker").datepicker({ 
      dateFormat: 'yyyy MM dd', 
      changeMonth: true, 
      changeYear: true, 
      changeDay: true, 
     }); 
    }); 
</script> 

<p> 
    @Html.ActionLink("Utwórz", "Create") 
</p> 

@{ 
    var fromDate = (DateTime)ViewBag.fromDate; 
    var toDate = (DateTime)ViewBag.toDate; 
} 

@using (Html.BeginForm("Index", "Oplatas", FormMethod.Get)) 
{ 
    <p> 
     Rodzaj oplaty: @Html.DropDownList("oplataTyp", "Wszystkie")<br /> 
     Numer rejestracyjny: @Html.TextBox("szukajRej") <br /> 
     Od: @Html.TextBox("fromDate", string.Format("{0:yyyy-MM-dd}", fromDate), new { @class = "DatePicker" }) 
     Do: @Html.TextBox("toDate", string.Format("{0:yyyy-MM-dd}", toDate), new { @class = "DatePicker" }) 
     <br /> 
     <input type="submit" value="Szukaj" /> 
    </p> 
} 

<br /> 
<table class="table"> 
    <tr> 
     <th> 
      @Html.DisplayNameFor(model => model.TablicaRejstracyjna) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.Pojazd.Marka) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.DataOplaty) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.PrzebiegOplaty) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.RodzajOplaty) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.KwotaOplaty) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.DodatkoweInformacjeOplaty) 
     </th> 
     <th></th> 
    </tr> 

    @foreach (var item in Model) 
    { 
     <tr> 
      <td> 
       @Html.DisplayFor(modelItem => item.TablicaRejstracyjna) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.Pojazd.Marka) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.DataOplaty) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.PrzebiegOplaty) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.RodzajOplaty) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.KwotaOplaty) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.DodatkoweInformacjeOplaty) 
      </td> 
      <td> 
       @Html.ActionLink("Edytuj", "Edit", new { id = item.ID }) | 
       @Html.ActionLink("Szczegóły", "Details", new { id = item.ID }) | 
       @Html.ActionLink("Usuń", "Delete", new { id = item.ID }) 
      </td> 
     </tr> 
    } 

</table> 

@if (ViewBag.SumowanieOplat != null) 
{ 
    <hr /> 
    <h2> 
     Suma kosztów: 
     @ViewBag.SumowanieOplat zł 
    </h2> 
    <hr /> 
} 
    Kliknij poniżej, aby wygenerować kompletny raport: 
@using (Html.BeginForm("ExportData", "Oplatas", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <table> 
     <tr><td></td><td><input type="submit" name="Export" id="Export" value="Generuj" /></td></tr> 

    </table> 
} 

ответ

0

Я довольно ржавый на использовании GridViews, но я верю в ваши ExportData функции, вы можете установить видимость столбца, например gv.Columns (4) .Visible = False

Надеюсь, это поможет!

+0

Что вы предлагаете вместо Gridviews? – DiPix

Смежные вопросы