我尝试将过滤后的webgrid导出为excel,但是当下载文件时,它会从数据库中获取所有记录,然后将我的代码更改为此。
此代码是我创建过滤器的页面:
var db = Database.Open("formIGF");
var query = "SELECT * FROM exportTable WHERE dataEncomenda LIKE @0 ";
var dataPedido = "%" + Request["dataPedido"] + "%";
var data = db.Query(query, dataPedido);
var columns = new[]{"dataEncomenda"};
var grid = new WebGrid(data, columnNames: columns, rowsPerPage:10);
<form method="post">
<div class="grid">
<div id="grid">
<label for="dataRecolha">Data do Pedido</label><input id="dataPedido" name="dataPedido" type="text" value="" placeholder="Selecionar um dia"/>
<input type="submit" />
@grid.GetHtml(
caption: "Numero Total de Entradas: " + @grid.TotalRowCount + " ",
tableStyle : "table",
alternatingRowStyle : "alternate",
headerStyle : "header",
columns: grid.Columns(
grid.Column("ID"),
grid.Column("dataEncomenda", "Data da Encomenda")
)
)
<a href="GenerateExcel.cshtml?cond=@Request["dataPedido"]" target="_blank">Exportar para Excel</a>
</div>
</div>
</form>
这是将导出到excel的页面的代码:
@{
Layout = null;
var db = Database.Open("formIGF");
var dataPedido = Request.QueryString["dataPedido"];
var data = db.Query(dataPedido);
var columns = data.First().Columns;
Response.AddHeader("Content-disposition", "attachment; filename=report.xls");
Response.ContentType = "application/octet-stream";
}
<table style="border: 1px solid #a59f9f;">
<tr style="font-weight: bold">
@foreach(var column in columns){
<td style="border: 1px solid #a59f9f;">@column</td>
}
</tr>
@foreach(var row in data){
<tr>
@foreach(var column in columns){
<td style="border: 1px solid #a59f9f;">@row[column]</td>
}
</tr>
}
</table>
然后我收到一个错误: 值不能为null或空字符串。参数名称:commandText
这意味着没有正确的传递值?
在我的网址上我得到了这个:
http://localhost:44552/GenerateExcel.cshtml?cond=04-06-2014
该值不应传递给我的查询字符串?
答案 0 :(得分:1)
您正在引用不存在的查询字符串值。您已将其命名为cond
,但正在使用Request.QueryString["dataPedido"]
来获取值。那应该是
var dataPedido = Request.QueryString["cond"];
不仅如此,您还可以将值作为SQL命令传递给Database.Query
方法。它不是有效的sql命令。您在更改中遗漏了这一点:
var query = "SELECT * FROM exportTable WHERE dataEncomenda LIKE @0 ";
var dataPedido = "%" + Request.QueryString["cond"] + "%";
var data = db.Query(query, dataPedido);