mvc 4 asp.net - 从本地.xls文件将数据导出到.csv

时间:2014-03-18 09:22:58

标签: asp.net-mvc asp.net-mvc-4 razor export-to-csv

如果您能帮我解决下面的代码,我将不胜感激:我对C#和Razor还不熟悉。我试图从Excel工作表中获取数据并使用jQuery Jtable在屏幕上显示它。我可以让它显示但不会将数据导出到CSV文件。我正在使用MVC 4 Razor ASP.NET

这是我的控制器操作代码:

    private void ExportToCsv(object sender, System.EventArgs e)
    {
        string Path = @"C:\\5Newwithdate.xls";

        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");

        OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);

        con.Close();

        System.Data.DataTable data = new System.Data.DataTable();

        da.Fill(data);

        SQLDBBillingProvider sql = new SQLDBBillingProvider();
    //    var billingList = sql.GetAllBilling(jtStartIndex, jtPageSize, jtSorting);

        //  data.Rows.OfType<DataRow>().Select(dr => dr.Field<MyType>(columnName)).ToList();

        List<TopPlayed> daa = new List<TopPlayed>();

        foreach (DataRow p in data.Rows)
        {
            //daa.Add(p.Field<string>("Track Statistics"));

            //daa.Add(p.Field<string>("Track Name"));

            TopPlayed top = new TopPlayed()
            {
                TrackID = p.Field<double>("ID").ToString(),
                TrackName = p.Field<string>("Track Name"),
                ArtistName = p.Field<string>("Artist Name"),
                Times = p.Field<double>("NoOfPlays").ToString()
            };

            daa.Add(top);
        }

        var toptracks = new List<TopPlayed>();

        // toptracks.Add(GetHeader());
        int k = -5;
        for (int i = 0; i < 5; i++)
        {
            //static data 
            var trackInfo = new TopPlayed();

            trackInfo.TrackID = "abc" + i;
            trackInfo.TrackName = "xyz" + i;
            trackInfo.ArtistName = "" + i;
            trackInfo.Times = "" + i;
            toptracks.Add(trackInfo);
        }
        System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
        gridvw.DataSource = toptracks.ToList().Take(7); //bind the datatable to the gridview
        gridvw.DataBind();
        Response.ClearContent();
        Response.ContentType = "application/vnd.ms-excel;name='Excel'";
        Response.AddHeader("content-disposition", "attachment;filename=TopTracks.csv");
        StringWriter swr = new StringWriter();
        HtmlTextWriter tw = new HtmlTextWriter(swr);
        gridvw.RenderControl(tw);
        Response.Write(swr.ToString());

        Response.End();
    }

提前致谢。

1 个答案:

答案 0 :(得分:1)

来自现有的,有效的项目:

   HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
   var sw = new StreamWriter(new MemoryStream());

   // Write the strings here..
   sw.WriteLine(...) etc

   // Flush the stream and reset the file cursor to the start
   sw.Flush();
   sw.BaseStream.Seek(0, SeekOrigin.Begin);

   // return the stream with Mime type
   return new FileStreamResult(sw.BaseStream, "text/csv");

只需调整变量以适合您的文件名和数据写入方法。

e.g。

   HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
   var sw = new StreamWriter(new MemoryStream());

   // Write the data here..
   HtmlTextWriter tw = new HtmlTextWriter(sw);
   gridvw.RenderControl(tw);

   // Flush the stream and reset the file cursor to the start
   sw.Flush();
   sw.BaseStream.Seek(0, SeekOrigin.Begin);

   // return the stream with Mime type
   return new FileStreamResult(sw.BaseStream, "text/csv");

在原始问题的上下文中,它将类似于:

    public ActionResult ExportToCsv()
    {
        string Path = @"C:\\5Newwithdate.xls";

        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");

        OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);

        con.Close();

        System.Data.DataTable data = new System.Data.DataTable();

        da.Fill(data);

        SQLDBBillingProvider sql = new SQLDBBillingProvider();
        //    var billingList = sql.GetAllBilling(jtStartIndex, jtPageSize, jtSorting);

        //  data.Rows.OfType<DataRow>().Select(dr => dr.Field<MyType>(columnName)).ToList();

        List<TopPlayed> daa = new List<TopPlayed>();

        foreach (DataRow p in data.Rows)
        {
            //daa.Add(p.Field<string>("Track Statistics"));

            //daa.Add(p.Field<string>("Track Name"));

            TopPlayed top = new TopPlayed()
            {
                TrackID = p.Field<double>("ID").ToString(),
                TrackName = p.Field<string>("Track Name"),
                ArtistName = p.Field<string>("Artist Name"),
                Times = p.Field<double>("NoOfPlays").ToString()
            };

            daa.Add(top);
        }

        var toptracks = new List<TopPlayed>();

        // toptracks.Add(GetHeader());
        int k = -5;
        for (int i = 0; i < 5; i++)
        {
            //static data 
            var trackInfo = new TopPlayed();

            trackInfo.TrackID = "abc" + i;
            trackInfo.TrackName = "xyz" + i;
            trackInfo.ArtistName = "" + i;
            trackInfo.Times = "" + i;
            toptracks.Add(trackInfo);
        }
        System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
        gridvw.DataSource = toptracks.ToList().Take(7); //bind the datatable to the gridview
        gridvw.DataBind();
        HttpContext.Response.ClearContent();
        HttpContext.Response.AddHeader("content-disposition", "attachment; filename=filename=TopTracks.csv");
        HttpContext.Response.AddHeader("Expires", "0");
        var sw = new StreamWriter(new MemoryStream());

        // Write the data here..
        HtmlTextWriter tw = new HtmlTextWriter(sw);
        gridvw.RenderControl(tw);

        // Flush the stream and reset the file cursor to the start
        sw.Flush();
        sw.BaseStream.Seek(0, SeekOrigin.Begin);

        // return the stream with Mime type
        return new FileStreamResult(sw.BaseStream, "text/csv");

    }