public void OutToWord() { if(dataGridview1.Rows.Count>1) { tempStr = “”; Stream myStream; SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = “(word文件)*.doc|*.doc”; dlg.FileterIndex = 2; dlg.RestoreDirectory = true; if(dlg.SaveFileDialog == DialogResult.OK) { if((myStream = dlg.OpenFile())!=null) { StreamWriter sw = new StreamWriter(myStream,Encoding.GetEncoding(“gb2312”)); string str=””; try { for(int i=0;i<dataGridView1.ColumnCount;i++) { if(i>0) str+=”\t\t”; str+=dataGridView1.Column[i].HeadText; } sw.WriteLine(str); for(int j=0;j<dataGridView1.Rows.Count -1 ;j++) { tempstr=””; for(int k=0;k<dataGridView1.ColumnsCount;k++) { if(k>0) tempStr+=”\t”; tempStr+=dataGridView1.Rows[j].Column[k].Value.ToString(); } sw.WriteLine(str); } MessageBox.Show(“成功导出到word”); } catch(Exception ex) { MessageBox.Show(ex.ToString()); } Finally { sw.Close(); myStream.Close(); } } } } |