use*_*821 5 c# sql-server stored-procedures export-to-excel
现在我的代码将它执行查询的所有列导出到excel文件中.执行的SQL命令位于存储过程中.我希望能够指定我要导出的SQL数据中的哪些列.
我想到的一种方法是让用户能够选择他们想要的东西,并将它们连接成SQL查询,而不是使用存储过程中的命令.
我还尝试将参数放入选择区域内的存储过程中,认为在选择字段中使用参数很简单,但据我所知,到目前为止,由于SQL注入的可能性,它是不允许的.
我已经看到一些人使用DataSet和DataTables来保存SQL数据,然后将所有数据导出到excel的例子.但是如果你以这种方式使用它,在写出该列之前你不需要检查一堆条件语句吗?
还有其他方法吗?下面的代码只是为了展示我到目前为止所做的事情.
private SqlDataSource GetDataSource(string FruitType)
{
SqlDataSource tempDataSource = new SqlDataSource();
tempDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["ServerConnectionString"].ToString();
tempDataSource.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
switch (ReportType)
{
case "Oranges":
tempDataSource.SelectCommand = "getOrange";
break;
case "Apples":
tempDataSource.SelectCommand = "getApples";
break;
case "Pineapples":
tempDataSource.SelectCommand = "getPineapples";
break;
case "Watermelons":
tempDataSource.SelectCommand = "getWatermelons";
break;
case "GrapeFruit":
tempDataSource.SelectCommand = "getGrapeFruit";
break;
}
tempDataSource.DataBind();
return tempDataSource;
}
protected void btnSaveData(object sender, EventArgs e)
{
string attachment = "attachment; filename=";
attachment += "Fruit Data";
attachment += ".xls";
Response.ClearContent();
Response.Charset = "";
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView gvTemp = new GridView();
gvTemp.Attributes["runat"] = "server";
SqlDataSource ds = GetDataSource(FruitType);
gvTemp.DataSource = ds;
gvTemp.DataBind();
gvTemp.RenderControl(htw);
Page.Controls.Add(gvTemp);
Response.Write(sw.ToString());
Response.End();
}
Run Code Online (Sandbox Code Playgroud)
您可以轻松地使用临时表来指定要从存储过程中获取哪些列:
CREATE PROCEDURE sp_GetDiffDataExample
@columnsStatement NVARCHAR(MAX) -- Needed columns
AS
BEGIN
DECLARE @query NVARCHAR(MAX)
SET @query = N'SELECT ' + @columnsStatement + N' INTO ##TempTable FROM dbo.TestTable'
EXEC sp_executeSql @query
SELECT * FROM ##TempTable
DROP TABLE ##TempTable
END
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
438 次 |
| 最近记录: |