简体   繁体   English

在特定位置导出和写入 CSV

[英]Export And Write CSV In Specific Location

I am stuck in a logic where I have following below requirement:我陷入了一个逻辑,我有以下要求:

1- Generate multiple CSV files. 1-生成多个 CSV 文件。

2- Export CSV files to a specific location. 2-将 CSV 文件导出到特定位置。

3- ZIP all the files from that location. 3-从该位置压缩所有文件。

Previously I had asked the question related to generate 2 files on a single button click here .以前我曾问过与单击此处生成 2 个文件有关的问题。 But later I found it's not possible to get two files from a single response in ASP.NET.但后来我发现不可能从 ASP.NET 中的单个响应中获取两个文件。 So I decided to Zip my files and download to the client's computer.所以我决定压缩我的文件并下载到客户的计算机上。 But I am generating my CSV files on button click and I have no specific location, So I decided to save my CSV file first on specific location and then ZIP the files.但是我在单击按钮时生成我的 CSV 文件并且我没有特定位置,所以我决定首先将我的 CSV 文件保存在特定位置,然后压缩文件。

Below is my code to generate my CSV file:下面是我生成 CSV 文件的代码:

using System.Data;
  using System.Data.SqlClient;
  using System.Text;
  using System.IO;
  using System;
  using System.Configuration;
  using System.IO.Packaging;
  using System.Web;

  namespace ExportToCsv
  {
  public partial class WebForm1 : System.Web.UI.Page
  {
  //Build the CSV file data as a Comma separated string.
  string csvHeader = string.Empty;
  //Build the CSV file data as a Comma separated string.
  string csvDetails = string.Empty; 

  protected void Page_Load(object sender, EventArgs e)
  {

  }

  protected void ExportCSV(object sender, EventArgs e)
  {
  string constr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
  using (SqlConnection con = new SqlConnection(constr))
  {
  using (SqlCommand cmd = new SqlCommand("select * from mytable-1")
  {
  using (SqlDataAdapter sda = new SqlDataAdapter())
  {
  cmd.Connection = con;
  sda.SelectCommand = cmd;
  using (DataTable dt = new DataTable())
  {
  sda.Fill(dt);


  //foreach (DataRow rows in dt.Rows)
  //{
  foreach (DataColumn column in dt.Columns)
  {
  //Add the Header row for CSV file.
  csvHeader += column.ColumnName + ' ';
  }


  //Add new line.
  csvHeader += "\r\n";

  foreach (DataRow row in dt.Rows)
  {
  foreach (DataColumn column in dt.Columns)
  {
  //Add the Data rows.
  csvHeader += row[column.ColumnName].ToString().Replace(",", ";") + ' ';
  }

  //Add new line.
  csvHeader += "\r\n";
  }
  //}

  Response.Clear();
  Response.Buffer = true;
  Response.AddHeader("content-disposition", "attachment;filename=HeaderSection.txt");
  Response.Charset = "";
  Response.ContentType = "application/text";
  Response.Output.Write(csvHeader); 
  }
  } 
  }

  using (SqlCommand cmd = new SqlCommand("select * from mytable-2")
  {
  using (SqlDataAdapter sda = new SqlDataAdapter())
  {
  cmd.Connection = con;
  sda.SelectCommand = cmd;
  using (DataTable dt = new DataTable())
  {
  sda.Fill(dt);


  //foreach (DataRow rows in dt.Rows)
  //{
  foreach (DataColumn column in dt.Columns)
  {
  //Add the Header row for CSV file.
  csvDetails += column.ColumnName + ' ';
  }


  //Add new line.
  csvDetails += "\r\n";

  foreach (DataRow row in dt.Rows)
  {
  foreach (DataColumn column in dt.Columns)
  {
  //Add the Data rows.
  csvDetails += row[column.ColumnName].ToString().Replace(",", ";") + ' ';
  }

  //Add new line.
  csvDetails += "\r\n";
  }
  //}

  // Download the CSV file.
  Response.Clear();
  Response.Buffer = true;
  Response.AddHeader("content-disposition", "attachment;filename=DetailSection.txt");
  Response.Charset = "";
  Response.ContentType = "application/text";
  Response.Output.Write(csvDetails);
  Response.Flush();
  Response.End();
  }
  }
  }
  }

  } 
  }
  }

I am able to achieve my 1st requirement but not able to achieve 2nd and 3rd.我能够达到我的第一个要求,但无法达到第二个和第三个要求。

Please help.请帮忙。 Thanks in advance.提前致谢。

I've been try your code, and you should change this part of your code,我一直在尝试您的代码,您应该更改代码的这一部分,

Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=HeaderSection.txt");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csvHeader);

To This,对此,

System.IO.File.WriteAllText("C://csvHeader.csv", csvHeader);

System.IO.File.WriteAllText will create file base on your string input, in this case your csvHeader and csvDetail , you also can change path "C://csvHeader.csv" to another specified location you want. System.IO.File.WriteAllText将根据您的字符串输入创建文件,在这种情况下是您的csvHeadercsvDetail ,您还可以将路径“C://csvHeader.csv”更改为您想要的另一个指定位置。

Then after all file you need created in that specified location, you can use System.IO.Compression to ZIP all csv you've created, or maybe you can use external library like Ionic Zip ,here some code i use if you are interested in using Ionic Zip Library ,然后在您需要在该指定位置创建所有文件之后,您可以使用System.IO.Compression对您创建的所有 csv 进行压缩,或者您可以使用像Ionic Zip这样的外部库,如果您有兴趣,我会使用一些代码使用Ionic Zip 库

using (ZipFile zip = new ZipFile())
{
   zip.AddFile("C://csvHeader.csv");
   zip.AddFile("C://csvDetail.csv");

   Response.ClearContent();
   Response.ClearHeaders();
   Response.AppendHeader("content-disposition", "attachment; filename=csv.zip");

   zip.Save(Response.OutputStream);
}

It should Download as Zip of your CSV它应该下载为 CSV 的 Zip

Edit : if you do not have specific location , you can use Path.GetTempPath()编辑:如果您没有特定位置,则可以使用Path.GetTempPath()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM