1 //DataGridView导出Excel 2 private void bt_Excl_Click(object sender, EventArgs e) 3 { 4 SaveFileDialog saveFileDialog = new SaveFileDialog(); 5 6 saveFileDialog.Filter = "Microsoft Excel 工作表 (.xls)|*.xls"; 7 saveFileDialog.FilterIndex = 0; 8 saveFileDialog.RestoreDirectory = true; 9 saveFileDialog.CreatePrompt = true;10 saveFileDialog.Title = "导出Excel文件到";11 DateTime now = DateTime.Now;12 saveFileDialog.FileName = now.Year.ToString().PadLeft(2) + now.Month.ToString().PadLeft(2, '0') + now.Day.ToString().PadLeft(2, '0') + "-" + now.Hour.ToString().PadLeft(2, '0') + now.Minute.ToString().PadLeft(2, '0') + now.Second.ToString().PadLeft(2, '0');13 saveFileDialog.ShowDialog();14 Stream myStream;15 myStream = saveFileDialog.OpenFile();16 StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));17 string str = "";18 try19 {20 //写标题21 for (int i = 0; i < dataTitl.ColumnCount; i++)22 {23 if (i > 0)24 {25 str += "\t";26 }27 str += dataTitl.Columns[i].HeaderText;28 }29 sw.WriteLine(str);30 //写内容31 for (int j = 0; j < dataTitl.Rows.Count; j++)32 {33 string tempStr = "";34 for (int k = 0; k < dataTitl.Columns.Count; k++)35 {36 if (k > 0)37 {38 tempStr += "\t";39 }40 tempStr += dataTitl.Rows[j].Cells[k].Value.ToString();41 }42 sw.WriteLine(tempStr);43 }44 sw.Close();45 myStream.Close();46 }47 catch (Exception)48 {49 MessageBox.Show("题目导出完成。", "导出", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);50 }51 finally52 {53 sw.Close();54 myStream.Close();55 }56 }