lijinchang

导航

DataGridView导出成excel实例

public void ExportExcel(object Sender, EventArgs e)
        {
            DataGridView dt = this.dataGridView1;
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可供导出,请先抓去数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                SaveFileDialog saveFileDialog2 = new SaveFileDialog();
                saveFileDialog2.Filter = "Execl2003 files (*.xls)|*.xls|Execl2007 files (*.xlsx)|*.xlsx";
                saveFileDialog2.FilterIndex = 0;
                saveFileDialog2.RestoreDirectory = true;
                saveFileDialog2.CreatePrompt = true;
                saveFileDialog2.Title = "导出文件保存路径";
                saveFileDialog2.FileName = null;
                saveFileDialog2.ShowDialog();
                string FileName = saveFileDialog2.FileName;

                if (FileName.Length != 0)
                {
                    //toolStripProgressBar1.Visible = true;


                    FileStream objFileStream;
                    StreamWriter objStreamWriter;
                    string strLine = "";
                    objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write,FileShare.ReadWrite);
                    objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
                    //toolStripProgressBar1.Value = 0;

                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        strLine = strLine + dt.Columns[i].HeaderText.ToString() + Convert.ToChar(9);

                    }
                    objStreamWriter.WriteLine(strLine);
                    strLine = "";

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        //strLine = strLine + (i + 1) + Convert.ToChar(9);
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            strLine = strLine + ((dt.Rows[i].Cells[j].Value == null) ? " " : dt.Rows[i].Cells[j].Value.ToString()) + Convert.ToChar(9);

                        }
                        objStreamWriter.WriteLine(strLine);
                        //toolStripProgressBar1.Value += 100 / dt.Rows.Count;
                        strLine = "";
                    }
                    objStreamWriter.Close();
                    objFileStream.Close();
                    MessageBox.Show("数据已经成功导出到:" + saveFileDialog2.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //toolStripProgressBar1.Value = 0;
                    //toolStripProgressBar1.Visible = false;
                }
            }

       
        }

posted on 2011-08-23 14:10  lijinchang  阅读(214)  评论(0编辑  收藏  举报