C# 從datagridview中匯出到excel

z32500086發表於2010-10-11

轉自 http://hi.baidu.com/%B6%FA%D7%D3/blog/item/9ef7050d6b9019216159f357.html

 

剛好用到這部分知識,在網上找了好久才找到個基本上能執行的,只為以後用著方便。。。  分享給會用到的朋友們。。。

 

 

 

 

如果要從C#中將一些內容匯出到Excel,有一個簡單的辦法,將下面的匯出方法放到當前form下,然後在匯出按鈕中呼叫它就可以了

 

首先,設定一個連線

private void Form1_Load(object sender, EventArgs e)
        {
            string M_str_sqlcon = "Data Source=***;DataBase=***;User id=***;pwd=***";
            string M_str_sqlstr = "select * from ***";
            SqlConnection myCon = new SqlConnection(M_str_sqlcon);
            try
            {
                myCon.Open();
                SqlDataAdapter sqlda = new SqlDataAdapter(M_str_sqlstr, myCon);
                DataSet myds = new DataSet();
                sqlda.Fill(myds);
                dataGridView1.DataSource = myds.Tables[0];
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

 

 

匯出方法:


        public static void ExportDataGridViewToExcel(DataGridView dataGridview1)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "匯出Excel檔案到";

            DateTime now = DateTime.Now;
            saveFileDialog.FileName = now.Year.ToString().PadLeft(2)
            + now.Month.ToString().PadLeft(2, '0')
            + now.Day.ToString().PadLeft(2, '0') + "-"
            + now.Hour.ToString().PadLeft(2, '0')
            + now.Minute.ToString().PadLeft(2, '0')
            + now.Second.ToString().PadLeft(2, '0');

            saveFileDialog.ShowDialog();

            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            string str = "";
            try
            {
                //寫標題   
                for (int i = 0; i < dataGridview1.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "/t";
                    }
                    str += dataGridview1.Columns[i].HeaderText;
                }

                sw.WriteLine(str);
                //寫內容
                for (int j = 0; j < dataGridview1.Rows.Count-1; j++)
                {
                    string tempStr = "";
                    for (int k = 0; k < dataGridview1.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            tempStr += "/t";
                        }
                        tempStr += dataGridview1.Rows[j].Cells[k].Value.ToString();
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }

 

 

 

 

 

呼叫方法:

private void button1_Click(object sender, EventArgs e)
        {
            this.ExportDataGridViewToExcel(dataGridView1);

        }

如果還需要其它檔案格式,可以在類中紅字地方加上你所要的檔案格式,如saveFileDialog.Filter = "Execl files (*.xls)|*.xls|All files (*.*)|*.*";

相關文章