[求助]DataGridView数据导出到Excel的问题
<p>哪位知道用流的方法把DataGridView数据导出到Excel时,如何写入指定的sheet中呢</p><p> public static void DataGridViewToExcel(DataGridView dgv)<br/> {<br/> <br/> SaveFileDialog dlg = new SaveFileDialog();<br/> dlg.Filter = "Execl files (*.xls)|*.xls";<br/> dlg.CheckFileExists = false;<br/> dlg.CheckPathExists = false;<br/> dlg.FilterIndex = 0;<br/> dlg.RestoreDirectory = true;<br/> dlg.CreatePrompt = true;<br/> dlg.Title = "保存为Excel文件";</p><p> if (dlg.ShowDialog() == DialogResult.OK)<br/> {<br/> Stream myStream;<br/> myStream = dlg.OpenFile();<br/> StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));<br/> string columnTitle = "";<br/> try<br/> {<br/> //写入列标题 <br/> for (int i = 0; i < dgv.ColumnCount; i++)<br/> {<br/> if (i > 0)<br/> {<br/> columnTitle += "\t";<br/> }<br/> columnTitle += dgv.Columns.HeaderText;<br/> }<br/> sw.WriteLine(columnTitle);</p><p> //写入列内容 <br/> for (int j = 0; j < dgv.Rows.Count; j++)<br/> {<br/> string columnValue = "";<br/> for (int k = 0; k < dgv.Columns.Count; k++)<br/> {<br/> if (k > 0)<br/> {<br/> columnValue += "\t";<br/> }<br/> if (dgv.Rows.Cells.Value == null)<br/> columnValue += "";<br/> else<br/> columnValue += dgv.Rows.Cells.Value.ToString().Trim();<br/> }<br/> sw.WriteLine(columnValue);<br/> }<br/> sw.Close();<br/> myStream.Close();<br/> }<br/> catch (Exception e)<br/> {<br/> MessageBox.Show(e.ToString());<br/> }<br/> finally<br/> {<br/> sw.Close();<br/> myStream.Close();<br/> }<br/> }<br/> }<br/></p> Google:Xml Excel <p>版主是说用流的方法不好吗?</p>
页:
[1]