我如何将数据从数据库写入文件 [英] How I Write Data From Databse To File

查看:62
本文介绍了我如何将数据从数据库写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从数据库中检索数据,这个数据我想保存在word,excel中。我怎么做到这一点。

i am retrieving data from database , this data i am want to save in word, excel . how i can do this.

推荐答案

通过谷歌搜索创建Excel电子表格c#,这是最常见的问题之一,有几千篇文章已经覆盖它了。



您可以使用Excel ODBC驱动程序或XML SDK,也可以自动化Excel应用程序本身,但这可能不适合取决于如何实际启动代码。
Start by googling "Create Excel spreadsheet c#", this is one of the most commonly-asked questions are there are literally thousands of articles covering it already.

You can use the Excel ODBC driver, or the XML SDK, or you can automate the Excel application itself, but that might not be suitable depending on how the code is actually launched.


有多种方法可以将Sql数据导出到Excel,使用OLEDB,Interop对象或使用内存流,你可以查看下面的代码片段

There are multiple ways to export Sql data to Excel, using OLEDB, Interop object or by using memory stream, you can check below snippet
protected void ExportExcel(object sender, EventArgs e)
{

    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    using (XLWorkbook wb = new XLWorkbook())
                    {
                        wb.Worksheets.Add(dt, "Customers");
                        Response.Clear();
                        Response.Buffer = true;
                        Response.Charset = "";
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                        Response.AddHeader("content-disposition", "attachment;filename=SqlExport.xlsx");
                        using (MemoryStream MyMemoryStream = new MemoryStream())
                        {
                            wb.SaveAs(MyMemoryStream);
                            MyMemoryStream.WriteTo(Response.OutputStream);
                            Response.Flush();
                            Response.End();
                        }
                    }
                }
            }
        }
    }
}


这篇关于我如何将数据从数据库写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆