c#数据库数据导出excel(百万级数据)

废话不多说,先上界面:

代码:

        private void button3_Click_1(object sender, EventArgs e)
        {
            DataSource ds = new DataSource();
            SqlConnection conn = ds.GetConn();
            conn.Open();
            DataTable dt1 = new DataTable();
            ClassGrid.ReturnData(gridControl1, gridView1);
            dt1 = ClassData.dt;
            //string strFile = "E:\test.csv";
            string path = @"E:\test3.csv";

            //File info initialization
           // strFile = "test";
            //strFile = strFile + DateTime.Now.ToString("yyyyMMddhhmmss");
            //strFile = strFile + ".csv";
           // path = System.Web.HttpContext.Current.Server.MapPath(strFile);



            System.IO.FileStream fs = new FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs, new System.Text.UnicodeEncoding());
            //Tabel header
            for (int i = 0; i < dt1.Columns.Count; i++)
            {
                sw.Write(dt1.Columns[i].ColumnName);
                sw.Write("\t");
            }
            sw.WriteLine("");
            //Table body
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                for (int j = 0; j < dt1.Columns.Count; j++)
                {
                    sw.Write(DelQuota(dt1.Rows[i][j].ToString()));
                    sw.Write("\t");
                }
                sw.WriteLine("");
            }
            sw.Flush();
            sw.Close();

            DownLoadFile(path);
        }

 private bool DownLoadFile(string _FileName)
        {
            try
            {
                System.IO.FileStream fs = System.IO.File.OpenRead(_FileName);
                byte[] FileData = new byte[fs.Length];
                fs.Read(FileData, 0, (int)fs.Length);
                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
                string FileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(_FileName));
                System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + System.Convert.ToChar(34) + FileName + System.Convert.ToChar(34));
                System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fs.Length.ToString());
                System.Web.HttpContext.Current.Response.BinaryWrite(FileData);
                fs.Close();
                System.IO.File.Delete(_FileName);
                System.Web.HttpContext.Current.Response.Flush();
                System.Web.HttpContext.Current.Response.End();
                return true;
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                return false;
            }
        }

 public string DelQuota(string str)
        {
            string result = str;
            string[] strQuota = { "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?" };
            for (int i = 0; i < strQuota.Length; i++)
            {
                if (result.IndexOf(strQuota[i]) > -1)
                    result = result.Replace(strQuota[i], "");
            }
            return result;
        }
  private void button4_Click(object sender, EventArgs e)
        {
            // 以字符流的形式下载文件
            string filePath = System.Web.HttpContext.Current.Server.MapPath("~/Upload/temp.xls");//路径
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            //删除文件,看个人喜好
            File.Delete(filePath);
            System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls", System.Text.Encoding.UTF8));
            System.Web.HttpContext.Current.Response.BinaryWrite(bytes);
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();
        }

对应的dll:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading.Tasks;
using System.Windows.Forms;

 

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用C#中的Microsoft.Office.Interop.Excel 库将SQL Server数据库数据导出Excel文件。以下是一个简单的示例代码: ``` using System; using System.Data; using System.Data.SqlClient; using System.IO; using Excel = Microsoft.Office.Interop.Excel; namespace ExportToExcel { class Program { static void Main(string[] args) { string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword"; string query = "SELECT * FROM myTable"; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand(query, connection)) { connection.Open(); SqlDataReader reader = command.ExecuteReader(); DataTable dataTable = new DataTable(); dataTable.Load(reader); Excel.Application excel = new Excel.Application(); excel.Visible = false; excel.DisplayAlerts = false; Excel.Workbook workbook = excel.Workbooks.Add(Type.Missing); Excel.Worksheet worksheet = workbook.ActiveSheet; for (int i = 0; i < dataTable.Columns.Count; i++) { worksheet.Cells[1, i + 1] = dataTable.Columns[i].ColumnName; } for (int i = 0; i < dataTable.Rows.Count; i++) { for (int j = 0; j < dataTable.Columns.Count; j++) { worksheet.Cells[i + 2, j + 1] = dataTable.Rows[i][j]; } } workbook.SaveAs("output.xlsx"); workbook.Close(); excel.Quit(); } } } } } ``` 其中,`connectionString`是数据库连接字符串,`query`是要执行的SQL查询语句,`output.xlsx`是导出Excel文件名。 请注意,为了使用`Microsoft.Office.Interop.Excel`库,你需要在Visual Studio中添加`Microsoft Excel 16.0 Object Library`引用。你可以在Visual Studio中的“项目”->“添加引用”菜单中找到它。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值