c# datagridview导出excel(写文本)

using System.IO;

        //导出到execl
        public void Excel(DataGridView dgv) 
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "Export Excel File";
            saveFileDialog.ShowDialog();
            if (saveFileDialog.FileName == "")
                return;
            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string str = "";
            try
            {
                //寫dataGridView1表標題
                for (int i = 0; i < dgv.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    str += dgv.Columns[i].HeaderText.Trim();
                }
                sw.WriteLine(str);

                //寫dataGridView1表內容
                for (int j = 0; j < dgv.Rows.Count; j++)
                {
                    string tempStr = "";
                    for (int k = 0; k < dgv.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            tempStr += "\t";
                        }
                        //tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString().Trim() ;
                        tempStr += dgv.Rows[j].Cells[k].Value;

                        //要增加對含數字的文字類,如身份証號
                        //.........欠對身份証號處理,以免在EXCEL打開時被自動轉數字
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }
 

  

posted @ 2012-08-26 13:34  一棍打出屁  阅读(1081)  评论(0编辑  收藏  举报