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(); }