private void DataToExecl() { if (this.dgTemp.Rows.Count > 0)//dgTemp为DataGridView控件 { SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "导出到Execl"; sfd.DefaultExt = "xls"; sfd.Filter = "Execl文件(*.xls)|.xls"; sfd.FilterIndex = 0; sfd.RestoreDirectory = true; sfd.CreatePrompt = true; sfd.FileName = "XXXX.xls";//导出xls的文件名 sfd.ShowDialog(); if (sfd.FileName == "") { return; } Stream stream = sfd.OpenFile(); StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0)); try { string str1 = ""; for (int i = 0; i < this.dgTemp.ColumnCount; i++) { if (str1 != "") { str1 += "\t"; } str1 += dgTemp.Columns[i].HeaderText; } sw.WriteLine(str1); for (int j = 0; j < dgTemp.Rows.Count; j++) { string str2 = ""; for (int k = 0; k < dgTemp.Columns.Count; k++) { if (str2 != "") { str2 += "\t"; } str2 += dgTemp.Rows[j].Cells[k].Value.ToString(); } sw.WriteLine(str2); } sw.Close(); stream.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { sw.Close(); stream.Close(); } } }