C#DataGridView의 데이터를 Excel로 내보내기

2803 단어 C#Exceldatagridview
public DataGridView _DataGridView=null;

        public void put(DataGridView _DataGridView)

        {

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";

            saveFileDialog.FilterIndex = 0;

            saveFileDialog.RestoreDirectory = true;

            saveFileDialog.CreatePrompt = true;

            saveFileDialog.Title = "** ";

            saveFileDialog.ShowDialog();

            if (saveFileDialog.FileName == "")

                return;

            Stream myStream;

            myStream = saveFileDialog.OpenFile();

            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));

 

            string str = "";

            try

            {

                for (int i = 0; i < _DataGridView.ColumnCount; i++)

                {

                    if (i > 0)

                    {

                        str += "\t";

                    }

                    str += _DataGridView.Columns[i].HeaderText;

                }

                sw.WriteLine(str);

                for (int j = 0; j < _DataGridView.Rows.Count; j++)

                {

                    string tempStr = "";

                    for (int k = 0; k < _DataGridView.Columns.Count; k++)

                    {

                        if (k > 0)

                        {

                            tempStr += "\t";

                        }

                        tempStr += _DataGridView.Rows[j].Cells[k].Value.ToString();

                    }

                    sw.WriteLine(tempStr);

                }

                sw.Close();

                myStream.Close();

            }

 

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString());

            }

            finally

            {

                sw.Close();

                myStream.Close();

                if (MessageBox.Show(" ! ?", " ...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)

                {

                    try

                    {

                        System.Diagnostics.Process process = new System.Diagnostics.Process();

                        process.StartInfo.FileName = saveFileDialog.FileName;

                        process.StartInfo.Verb = "Open";

                        process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;

                        process.Start();

                    }

                    catch

                    {

                        MessageBox.Show(" Excel, !");

                    }

                }

좋은 웹페이지 즐겨찾기