2011-09-21 3 views
2
protected void btnDownload_Click(object sender, EventArgs e) 
{ 
    SqlCommand Command = connection.CreateCommand(); 
        SqlDataReader SQLRD; 
        Command.CommandText = "Select *from Attendance"; 
        connection.Open(); 
     SQLRD = Command.ExecuteReader();    
     string data = ""; 
      while (SQLRD.Read()) 
     { 
      data += SQLRD[0].ToString(); 
      data += SQLRD[1].ToString(); 

     } 

     SQLRD.Close(); 
     connection.Close(); 

     string filename = @"C:\download.csv"; 
     FileStream fs = new FileStream(filename,FileMode.Append, FileAccess.Write); 
     StreamWriter sw = new StreamWriter(fs); 
     sw.WriteLine(data); 
     sw.Flush(); 
     sw.Close(); 
     fs.Close(); } 

이것은 내가 지금까지 가지고있는 것입니다. 위 쿼리의 모든 데이터를 파일에 저장하려고합니다. 이 파일이 다운로드됩니다.데이터베이스의 모든 세부 정보를 파일로 저장하고 나중에 파일을 다운로드하십시오.

+0

어떤 종류의 영혼을 도울 수 있습니까? – Mark20

답변

1
protected void btnDownload_Click(object sender, EventArgs e) 
{ 
    MySqlConnection connection = new MySqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true"); 

    MySqlCommand myCommand = myConn.CreateCommand(); 
    MySqlDataReader SQLRD; 
    myCommand.CommandText = "SELECT * FROM Attendance"; 
    connection.Open(); 
    SQLRD = myCommand.ExecuteReader(); 
    string data=""; 
    while (SQLRD.Read()) 
    { 
    data += "Row data, arrange how you want";//SQLRD[0].Tostring();-->first coloum 
    } 
    SQLRD.Close(); 
    connection.Close(); 

    string filename = "F:\file1.txt"; //with path 
    FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write); 
    StreamWriter sw = new StreamWriter(fs); 
    sw.WriteLine(data); 
    sw.Flush(); 
    sw.Close(); 
    fs.Close(); 
} 

편집을 할 CODE : 그냥 가장 직렬화를 사용하여 제공 될 것이다

  MySqlCommand Command = connection.CreateCommand(); 
      connection.Open(); 
      //SqlCommand Command = new SqlCommand(); 
      MySqlDataReader SQLRD; 
      Command.CommandText = "Select * from Attendance"; 
      //connection.Open(); 
      SQLRD = Command.ExecuteReader(); 
      string data = ""; 
      while (SQLRD.Read()) 
      { 
       data += SQLRD[0].ToString()+"\n"; 
       data += SQLRD[1].ToString()+"\n"; 

      } 

      SQLRD.Close(); 
      connection.Close(); 

      string filename = @"F:\download.csv"; 
      FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write); 
      StreamWriter sw = new StreamWriter(fs); 
      sw.WriteLine(data); 
      sw.Flush(); 
      sw.Close(); 
      fs.Close(); 
     } 
+0

안녕하세요, 정말 고마워요! 그러나 "string filename ="F : \ file1.txt ";"에서 오류가 발생합니다.이 오류는 인식 할 수없는 이스케이프 시퀀스라고 말하면서이 점을 이해하지 못합니다. 어떻게이 오류를 해결할 수 있습니까? – Mark20

+0

문자열 filename = "F : \\ file1.txt"; 또는 FileStream fs = new FileStream (@filename, FileMode.Append, FileAccess.Write); 당신이 할 수있는 어떤 사람 – deepi

+0

하나의 마지막 질문을 할 수 있습니까? 한 행의 데이터 만 가져올 수 있으며 9 행의 데이터를 가져오고 싶습니다. 어떻게해야합니까? 죄송 당신을 – Mark20

0

코드 및 변경 파일 이름 경로에 붙여 넣기를 복사합니다. 나는 Active Record 디자인 패턴을 사용하여 구조화 된 객체를 만들 것입니다.

그런 다음 XML 직렬화를 사용하여 해당 객체를 XML 객체로 출력합니다. 그 XML을 디스크에 저장하고 나중에 비 직렬화하여 아무 일도 일어나지 않는 것처럼 사용할 것입니다.

은 참조 : How to serialize and object to XML in C# on MSDN.

0

나중에 다운로드 할 수 있습니다 DataTable.WriteXml XML 파일로 데이터 테이블의 전체 데이터를 기록하는 방법과이 파일을 사용하고있는 파일에 기록하는 가장 쉬운 방법 :

SqlDataAdapter sqlAdap = new SqlDataAdapter(query, connection); 
DataTable dt = new DataTable(); 
sqlAdap.Fill(dt); 

string filePath = Server.MapPath("~/filename.xml"); 
dt.WriteXml(filePath); 

을하지만 당신은이 데이터를 기록 할 경우 어떤 특정 형식, 예를 들어 CSV, 당신은 모든 행을 반복해야하고 StreamWrite 클래스를 사용하여 파일에 쓸 수 있습니다. 아래 코드는 당신에게 아이디어를주기위한 것으로, 어떤 타입 체크도 추가하지 않았거나 null을 체크하지 않았습니다.

string filePath = Server.MapPath("~/somefile.csv"); 
System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath); 

foreach (DataRow r in dt.Rows) 
{ 
     for (int i = 0; i < dt.Columns.Count; i++) 
     { 
      sw.Write(r[i].ToString()); 
      sw.Write(","); 
     } 

     sw.WriteLine(); 
} 
sw.Close(); 
0

이 같은 디스크에 DataSet로 내보낼 수 있습니다 원하는 파일 형식을 기반으로 변경됩니다 파일에 데이터를 저장하는

using (var conn = new SqlConnection(@"<your conn str>")) 
{ 
    var ds = new DataSet(); 
    using (var invoiceCmd = conn.CreateCommand()) 

    //One of these per table to export 
    using(var invoiceAdapter = new SqlDataAdapter(invoiceCmd)) 
    { 
     invoiceCmd.CommandText = "SELECT * FROM Attendance"; 
     invoiceAdapter.Fill(ds, "Attendance"); 
    } 

    ds.WriteXml(@"C:\temp\foo.xml"); 
} 
1

코드를. 파일을 저장하고 나면 HttpResponse.TransmitFile을 사용하여 파일을 브라우저로 푸시합니다. 예를 들어, 템플릿 코드는

protected void btnDownload_Click(object sender, EventArgs e) 
{ 
    SqlConnection connection = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true"); 

    string query = "SELECT * FROM Attendance"; 

    // Fetch data using data reader or data adapter 
    ... 

    // Save the data to file in required format 
    string filePath; 
    .... 

    // Push the file from response 
    Response.ContentType = "text/csv"; // set as per file type e.g. text/plain, text/xml etc 
    Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv"); // will prompt user for save file dialog, use inline instead of attachment to suppress the dialog 
    Response.TransmitFile(filePath); 
} 

xml/csv와 같은 형식으로 파일을 저장하는 코드에 대한 다른 답변을 참조하십시오.

관련 문제