My Name is Kay....

DIY , 먹방 , 개발 , 육아 , 여행 좋아합니다.
AdBlock 사용시 화면이 정상적으로 노출되지 않습니다.
포스팅 관련 문의 및 개발 문의는 Email : wkzkfmxksi@gmail.com

추가 포스팅이 이뤄지지 않는 블로그입니다. 문의는 wkzkfmxksi@gmail.com 으로 연락주세요.
kay
조회 수 4347 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

SQL 쿼리로 Excel 파일 내보내기 샘플입니다.


기존에 DataGridView 를 내보내는것을 약간 수정했습니다.   ( 엑셀 내보내기 , Exporting DataGridview To Excel : http://www.uhoon.co.kr/dotnet/1897 )



  private void button1_Click(object sender, EventArgs e) {
  	SaveFileDialog sfd = new SaveFileDialog();
  	sfd.Filter = "Excel Documents (*.xls)|*.xls";
  	sfd.FileName = "fileName.xls";
  	if (sfd.ShowDialog() == DialogResult.OK) { 
  		ToCsV(sfd.FileName);  
  	}
  }
  private void ToCsV(string filename) {
  	string stOutput = "";
  	string sHeaders = "";
  	string SQL = "SELECT * FROM *********";
  	SqlConnection conn = new SqlConnection(ConnectionString);
  	conn.Open();
  	SqlCommand cmd = new SqlCommand(SQL, conn);
  	SqlDataReader dr = cmd.ExecuteReader();
  	// Loop through the fields and add headers
  	for (int i = 0; i < dr.FieldCount; i++) {
  		string name = dr.GetName(i);
  		sHeaders = sHeaders.ToString() + name.ToString() + "\t";
  	}
  	stOutput += sHeaders + "\r\n";
  	// Loop through the rows and output the data
  	while (dr.Read()) {
  		string stLine = "";
  		for (int i = 0; i < dr.FieldCount; i++) {
  			string value = dr[i].ToString();
  			stLine = stLine.ToString() + value.ToString() + "\t";
  		}
  		stOutput += stLine + "\r\n";
  	}
  	Encoding utf16 = Encoding.GetEncoding(1254);
  	byte[] output = utf16.GetBytes(stOutput);
  	FileStream fs = new FileStream(filename, FileMode.Create);
  	BinaryWriter bw = new BinaryWriter(fs);
  	bw.Write(output, 0, output.Length); //write the encoded file
  	bw.Flush();
  	bw.Close();
  	fs.Close();
  }
?

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
1 VB 파일 읽기 , 복사 , 삭제 , 쓰기 , 파일 유무 kay 2013.09.27 3950
Board Pagination Prev 1 Next
/ 1