当前位置:编程学习 > C#/ASP.NET >>

ADO.net 中如何将sql数据库某个表的信息导出到记事本文档里面(excel也行)?

在form表中,有个已经加载某个表信息的dataGridView1,一个button1,点击button时将此表的信息保存在电脑的txt文档或excel表里面,弄了几天,一直没成,在这里求高手帮忙.谢了 --------------------编程问答-------------------- private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl  files  (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;  //提示是否创建(*****).xls文件 
            saveFileDialog.Title = "导出Excel文件到";

            // saveFileDialog.ShowDialog(); 
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stream myStream;
                myStream = saveFileDialog.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));

                string str = "";
                try
                {
                    //写标题    
                    for (int i = 0; i < dgvAuthors.ColumnCount; i++)
                    {
                        if (i > 0)
                        {
                            str += "\t";
                        }
                        str += dgvAuthors.Columns[i].HeaderText;
                    }

                    sw.WriteLine(str);
                    //写内容  
                    for (int j = 0; j < dgvAuthors.Rows.Count - 1; j++)
                    {
                        string tempStr = "";
                        for (int k = 0; k < dgvAuthors.Columns.Count; k++)
                        {
                            if (k > 0)
                            {
                                tempStr += "\t";
                            }
                            tempStr += dgvAuthors.Rows[j].Cells[k].Value.ToString();
                        }
                        sw.WriteLine(tempStr);
                    }

                    MessageBox.Show("导出数据成功");
                    sw.Close();
                    myStream.Close();

                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message);
                    return;
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }

        }
补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,