显示“另存为”对话框,用于下载CSV文件

时间:2011-11-12 06:38:46

标签: asp.net csv

我的CSV代码是: -

public void CreateCSVFile(DataTable dt, string strFilePath)
{
    StreamWriter sw = new StreamWriter(strFilePath, false);
    int iColCount = dt.Columns.Count;
    for (int i = 0; i < iColCount; i++)
    {
        sw.Write(dt.Columns[i]);
        if (i < iColCount - 1)
        {
            sw.Write(",");
        }

    }
    sw.Write(sw.NewLine);
    // Now write all the rows.
    foreach (DataRow dr in dt.Rows)
    {
        for (int i = 0; i < iColCount; i++)
        {
            if (!Convert.IsDBNull(dr[i]))
            {
                string email = dr[i].ToString();
                bool result = IsEmail(email);
                if (result == true)
                    sw.Write(dr[i].ToString());
            }
            //if (i < iColCount - 1)
            //{
            //    sw.Write(" , ");
            //}
        }

        sw.Write(sw.NewLine);
    }
    sw.Close();

}

并在grid_RowCommand()上执行此操作...

if (e.CommandName == "cmdCSV")
    {
        DataTable dtCSV = new DataTable();
        dtCSV = ob.TotalRecord(TableField, TableName);

        CreateCSVFile(dtCSV, "c:\\csv file/csv "+TableName+".csv");
        lblMsg.Visible = true;
        lblMsg.Text = "CSV File Successfully created in C.";
        lblMsg.ForeColor = Color.Green;
    }

此处CreateCSVFile(dtCSV, "c:\\csv file/csv "+TableName+".csv");在c中下载CSV文件bydefault。我想在我要保存的位置下载CSV文件。我该怎么做?请指导我。

提前致谢

1 个答案:

答案 0 :(得分:2)

试试这个

Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=XYZ.csv");
string newpath2 = System.Web.HttpContext.Current.Server.MapPath("~//downloadfile//XYZ.csv");
FileStream sourceFile = new FileStream(newpath2, FileMode.Open);
long FileSize;
FileSize = sourceFile.Length;
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();

OR

string filePath = Server.MapPath("~/files/myFileName.csv");
    System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\\\"{0}\\\"", filePath));
    Response.AddHeader("Content-Length", fileInfo.Length.ToString());
    Response.WriteFile(filePath);
    Response.End();