csv导出在CSV文件中显示HTML标记,仅显示一条记录

时间:2014-03-21 13:52:10

标签: c# asp.net-mvc export-to-csv razorengine

如果您可以帮我解决以下代码,我将非常感激..我可以阅读本地.xls文件并使用jQuery jTable在浏览器上显示它,我也可以将数据导出到.csv文件但是某种原因,它在下载的文件中显示HTML标签,我认为这是由于使用

HtmlTextWriter tw = new HtmlTextWriter(sw);
gridvw.RenderControl(tw); 

此外,它仅在下载.CSV文件时显示一条记录。我尝试使用TextWriter但未显示任何内容。

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();
    List<TopPlayed> daa = new List<TopPlayed>();

    foreach (DataRow p in data.Rows)
    {
        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()
        };

        System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
        gridvw.DataSource = top.ArtistName.ToList().Take(7); 
        gridvw.DataBind();
        HttpContext.Response.ClearContent();
        HttpContext.Response.AddHeader("content-disposition", "attachment; 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");
    }

    return View();
}

download csv file

2 个答案:

答案 0 :(得分:2)

这么多问题,时间很少:

你根本不想写出一个网格。这适用于您的Web视图,但可以直接从数据生成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();
    List<TopPlayed> daa = new List<TopPlayed>();

    // Create a memory stream and a TextWriter that uses it for its output
    var sw = new StreamWriter(new MemoryStream());
    TextWriter tw = new TextWriter(sw);

    // Write the header row
    tw.WriteLine("\"ID\", \"Track\", \"Artist\", \"Plays\"");

    // Write the data here..
    foreach (DataRow p in data.Rows)
    {
        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()
        };
        // Write a single CSV line
        tw.WriteLine(string.Format("\"{0}\", \"{1}\", \"{2}\", \"{3}\"", top.TrackID, top.TrackName, top.ArtistName, top.Times);
    }

    // Now return the stream to the client/browser    
    HttpContext.Response.ClearContent();
    HttpContext.Response.AddHeader("content-disposition", "attachment; filename=TopTracks.csv");
    HttpContext.Response.AddHeader("Expires", "0");
    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");

}

你实际上并不需要TopPlayed对象,但我不想一次改变太多:)

那可能会成为:

// Write the data here..
foreach (DataRow p in data.Rows)
{
    // Write a single CSV line direct from the database record
    tw.WriteLine(string.Format("\"{0}\", \"{1}\", \"{2}\", \"{3}\"", p.Field<double>("ID"), p.Field<string>("Track Name"), p.Field<string>("Artist Name"), p.Field<double>("NoOfPlays"));
}

请注意,您的连接字符串中不需要(char)34。这代表双引号。只需使用2个双引号""(在@ -style字符串中)或\“(在普通字符串中)转义任何双引号。

e.g。

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

又一个版本:

此外,正如John Saunders决定使用向下推荐指出,您应该始终在IDisposable语句中包含实现using的对象,以确保它们是当它们超出范围时正确/自动关闭。如果您的SQLDBBillingProvider实施IDisposable它还应该有using

我还注意到我不需要额外的TextWriter isa StreamWriter(即它直接继承TextWriter)。

请注意我无法编译此代码,因为我没有丢失的部分,所以可能有奇怪的错误:

public ActionResult ExportToCsv()
{
    string Path = @"C:\\5Newwithdate.xls";
    using (OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + ""))
    {
        using (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();
            List<TopPlayed> daa = new List<TopPlayed>();

            // Create a memory stream and a TextWriter that uses it for its output
            using (var sw = new StreamWriter(new MemoryStream()))
            {
                // Write the header row
                sw.WriteLine("\"ID\", \"Track\", \"Artist\", \"Plays\"");

                // Write the data here..
                foreach (DataRow p in data.Rows)
                {
                    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()
                    };
                    // Write a single CSV line
                    sw.WriteLine(string.Format("\"{0}\", \"{1}\", \"{2}\", \"{3}\"", top.TrackID, top.TrackName, top.ArtistName, top.Times);
                }
                // Now return the stream to the client/browser    
                HttpContext.Response.ClearContent();
                HttpContext.Response.AddHeader("content-disposition", "attachment; filename=TopTracks.csv");
                HttpContext.Response.AddHeader("Expires", "0");
                // 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");
            }
        }
    }
}

答案 1 :(得分:0)

我不得不调整这段代码,因为它给了我错误说“无法创建抽象类的实例或接口System.IO.TextWriter”所以从

  var sw = new StreamWriter(new MemoryStream());
  TextWriter tw = new TextWriter(sw);

到这个

    var tw = new StreamWriter(new MemoryStream());
 // TextWriter tw = new TextWriter(sw);

一小部分,在CSV文件中,记录显示在“”之间,而不是它很棒:)