日期:2014-05-18  浏览次数:20895 次

C#将DataGridView中的数据导出到Excel当中
        public static void ExportDataGridViewToExcel(DataGridView dataGridview1)
        {
            if (dataGridview1.Rows.Count == 0)
            {
                MessageBox.Show("数据库当中没有任何记录");
            }
            else
            {

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.CreatePrompt = true;
                saveFileDialog.Title = "导出Excel文件到";
                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);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message.ToString());
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }
        }