当前位置:   article > 正文

C#之将查询到SQL Server数据导出为文件保存_c#如何导出sql压缩包

c#如何导出sql压缩包

1. 运行效果

首先从SQL Server数据库检索查询自己想要的数据

在这里插入图片描述
然后点击导出数据,选择自己需要的文件格式

在这里插入图片描述
可以看到这个时候文件已经导出为Excel保存在电脑上

在这里插入图片描述
还可以导出为文本文件,如下图

在这里插入图片描述

2.主要代码

 public static void SaveDataGridViewToFile(DataGridView dataGridView)
        {
            //新建文件保存对话框对象
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            //设置文件保存的类型
            saveFileDialog.Filter = "Excel files (*.xls)|*.xls|Word files (*.doc)|*.doc|(*.txt)|*.txt|all files (*.*)|*.*";

            //当文件不存在时,提示用户是否创建该文件
            saveFileDialog.CreatePrompt = true;
 
            //当用户点击保存按钮后执行流写入操作
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                //打开文件流
                StreamWriter streamWriter = new StreamWriter(saveFileDialog.OpenFile(), Encoding.GetEncoding(0));
                string writerString = "";

                //填充字段名称
                for (int k = 0; k < dataGridView.ColumnCount; k++)
                {
                    writerString += dataGridView.Columns[k].HeaderText;
                    writerString += "\t";
                }
                writerString += "\n";

                //填充数据
                for (int i = 0; i < dataGridView.RowCount; i++)
                {
                    if (i > 0)
                    {
                        writerString += "\n";
                    }
                    for (int j = 0; j < dataGridView.ColumnCount; j++)
                    {
                        if (j > 0)
                        {
                            writerString += "\t";
                        }
                        if (dataGridView[j, i].Value != null)
                        {
                            writerString += dataGridView[j, i].Value.ToString();
                        }
                    }
                }

                //将字符串写入流
                streamWriter.WriteLine(writerString);

                //关闭当前流
                streamWriter.Close();
            }            
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/458333
推荐阅读
相关标签
  

闽ICP备14008679号