【问题标题】:Moving data from SQL Server to Excel using C#使用 C# 将数据从 SQL Server 移动到 Excel
【发布时间】:2016-02-23 15:33:36
【问题描述】:

我正在尝试使用 WinForms 通过 C# 表单将数据从 SQL Server 2012 移动到 Excel 2010。我拥有的数据包含一个名为“上诉”的列,我想在 Excel 工作簿中为其创建单独的工作表。我想用“上诉”的名称标记标签。我似乎无法获得的部分实际上是将数据放入我刚刚创建和标记的相关选项卡中。有更多经验的人可以帮助我吗?请注意,表格和值是实际表格的简化版本。

CREATE TABLE [dbo].[Appeals](
    [Appeal] [nchar](10) NULL,
    [Member_ID] [varchar](10) NULL,
    [Amount] [money] NULL,
    [DateGiven] [date] NULL
) ON [PRIMARY]


insert into Appeals values ('6Y','101',50,'2-15-2016')
insert into Appeals values ('6Y','209',100,'2-14-2016')
insert into Appeals values ('6Y','218',200,'2-12-2016')
insert into Appeals values ('7G','102',300,'1-15-2016')
insert into Appeals values ('7G','209',20,'2-21-2016')
insert into Appeals values ('WR','108',50,'1-22-2016')
insert into Appeals values ('WR','198',100,'1-29-2016')
insert into Appeals values ('WR','303',500,'1-31-2016')
insert into Appeals values ('WR','312',150,'7-19-2016')


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel; 


       private void button7_Click(object sender, EventArgs e)
        {
            SqlConnection cnn;
            string connectionString = null;

            object misValue = System.Reflection.Missing.Value;

            connectionString = "data source=D7010-H14NBZ1\\SQLEXPRESS;initial catalog=iTest;user id=TestUser;password=testPW;";
            StringBuilder query = new StringBuilder();

            cnn = new SqlConnection(connectionString);
            cnn.Open();
            query.Append("SELECT        Appeal, Member_ID, ");
            query.Append("Amount, DateGiven ");
            query.Append("FROM  dbo.Appeals ");
            query.Append("WHERE        (Appeal IN (N'6Y', N'7G', N'WR')) ");
            query.Append("ORDER BY Appeal DESC");
            SqlDataAdapter dscmd = new SqlDataAdapter(query.ToString(), cnn);
            DataTable dt = new DataTable();
            dscmd.Fill(dt);

            Excel.Application oXL;
            Excel._Workbook oWB;
            Excel._Worksheet oSheet;

            oXL = new Excel.Application();
            oXL.Visible = true;

            oWB = (Excel._Workbook)(oXL.Workbooks.Add(misValue));
            oSheet = (Excel._Worksheet)oWB.ActiveSheet;

            try
            {
                DataTable dtAppCode =
                        dt.DefaultView.ToTable(true, "Appeal");

                foreach (DataRow appcode in dtAppCode.Rows)
                {
                    oSheet = (Excel._Worksheet)oXL.Worksheets.Add();
                    oSheet.Name = appcode[0].ToString().Replace(" ", "").
                        Replace("  ", "").Replace("/", "").
                            Replace("\\", "").Replace("*", ""); ;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                GC.Collect();
            }

            oXL.Visible = true;
            oXL.UserControl = true;

            oWB.SaveAs(@"H:\Appeals2.xlsx",
                AccessMode: Excel.XlSaveAsAccessMode.xlShared);

        }
      }
    }

【问题讨论】:

标签: c# sql-server excel winforms


【解决方案1】:

这被称为使用 C# 将数据从 SQL 数据库导出到 Excel。这真的很容易实现和理解。

CodePlex 提供称为 ClosedXML 的 API。你可以在这里找到它:https://closedxml.codeplex.com/

ClosedXML 允许创建不同的工作簿和工作表来导出 SQL 数据。

使用 ClosedXML DLL,您可以非常轻松地导出数据。

protected void button7_Click(object sender, EventArgs e)
    {
    string connectionstring;

    connectionstring = """data source=D7010-H14NBZ1\\SQLEXPRESS;initial catalog=iTest;user id=TestUser;password=testPW;";

    string query = "SELECT Appeal, Member_ID, Amount, DateGiven FROM  dbo.Appeals WHERE Appeal IN (N'6Y', N'7G', N'WR') ORDER BY Appeal DESC";

    SqlConnection connection = new SqlConnection(connectionstring);
        connection.Open();

        SqlCommand command = new SqlCommand(query, connection);

        DataTable data = new DataTable();

        using (SqlDataAdapter a = new SqlDataAdapter(command))
        {
            a.Fill(data);
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(data, "Excel Export");

                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=Excel Export.xlsx");
                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(Response.OutputStream);
                    Response.Flush();
                    Response.End();
                }
            }
        }
}

这肯定会帮助你:)

【讨论】:

  • 感谢 ClosedXML 的建议。看起来这可以很好地工作。一个问题,当我下载它时,我将dll文件解压到哪个目录?我将如何注册 dll 文件?
  • 您需要从我之前提供的链接下载 .zip 文件。提取文件。它将为您提供 ClosedXML.dll 文件。只需通过 Visual Studio 中的添加引用部分将 .dll 文件添加到您的 C# 项目中。
  • 如果您需要有关此问题的任何其他帮助,请随时与我联系。 :)
  • 谢谢朱奈德。我已经添加了“使用 ClosedXML.Excel;”,但是我需要添加什么才能识别 Response 和 Memorystream 引用?
  • 对于响应,您应该使用 System.Web.HttpException 添加;对于 MemoryStream,您应该使用 System.IO 添加;
【解决方案2】:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using Excel = Microsoft.Office.Interop.Excel; 

    namespace WindowsFormsApplication8
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                SqlConnection cnn;
                string connectionString = null;
                string data = null;
                int i = 0;
                int j = 0;
                int h = 1;
                int Appeal_ID = 20;
                object misValue = System.Reflection.Missing.Value;

                label1.Text = "Processing......";

                connectionString = "data source=D7010-H14NBZ1\\SQLEXPRESS;initial catalog=itest;user id=xxxx;password=xxxx;";
                StringBuilder query = new StringBuilder();

                cnn = new SqlConnection(connectionString);
                cnn.Open();

                Excel.Application oXL;
                Excel._Workbook oWB;
                Excel._Worksheet oSheet;

                oXL = new Excel.Application();
                oWB = (Excel._Workbook)(oXL.Workbooks.Add(misValue));
                oSheet = (Excel._Worksheet)oWB.ActiveSheet;

                for (h = 48; h >= 1; h--)
                {
                    query.Append("SELECT     TOP (100) PERCENT dbo.FDN_GivingAppeal_Main.Appeal_ID, dbo.FDN_GivingAppeal_Main.ID, dbo.FDN_GivingAppeal_Main.Appeal,                 dbo.vBoCsContact.MemberType, ");
                    query.Append("dbo.vBoCsContact.Title, dbo.vBoCsContact.Prefix, dbo.vBoCsContact.FirstName, dbo.vBoCsContact.MiddleName AS MI, dbo.vBoCsContact.LastName, ");
                    query.Append("dbo.vBoCsContact.Suffix, dbo.vBoCsContact.Designation, dbo.vBoCsContact.Informal, dbo.vBoCsContact.Email, dbo.vBoCsContact.Company, ");
                    query.Append("dbo.vBoCsAddress.Address1, dbo.vBoCsAddress.Address2, dbo.vBoCsAddress.City, dbo.vBoCsAddress.StateProvince, dbo.vBoCsAddress.Zip, ");
                    query.Append("dbo.vBoCsAddress.Country, dbo.vBoCsAddress.Phone, dbo.FDN_GivingAppeal_Main.Amount AS YrTotal_LastGivingYr,               dbo.FDN_GivingAppeal_Main.LastTransDate, ");
                    query.Append("dbo.FDN_GivingAppeal_Main.LastTransAmt, dbo.FDN_GivingAppeal_Main.LargestGiving, dbo.FDN_GivingAppeal_Main.LifetimeTotal, ");
                    query.Append("dbo.FDN_GivingAppeal_Main.FiscalYear AS LastGivingYr, dbo.FDN_GivingAppeal_Main.CapitalCampaign, dbo.FDN_GivingAppeal_Main.P2GScore, ");
                    query.Append("dbo.FDN_GivingAppeal_Main.InnerCircle ");
                    query.Append("FROM         dbo.FDN_GivingAppeal_Main INNER JOIN ");
                    query.Append("dbo.FDN_AppealCode_Sort ON dbo.FDN_GivingAppeal_Main.Appeal_ID = dbo.FDN_AppealCode_Sort.ID AND  ");
                    query.Append("dbo.FDN_GivingAppeal_Main.Appeal = dbo.FDN_AppealCode_Sort.Appeal_code INNER JOIN  ");
                    query.Append("dbo.vBoCsContact ON dbo.FDN_GivingAppeal_Main.ID = dbo.vBoCsContact.ID INNER JOIN ");
                    query.Append("dbo.vBoCsAddress ON dbo.vBoCsContact.ID = dbo.vBoCsAddress.ID ");
                    query.Append("WHERE    (dbo.vBoCsAddress.PreferredMail = 1) AND (dbo.vBoCsAddress.BadAddress <> 'BAD') AND  (dbo.FDN_GivingAppeal_Main.Appeal_ID = " +              Appeal_ID + ") AND   Appeal_Sort in(" + h + ") ");
                    query.Append("ORDER BY dbo.FDN_AppealCode_Sort.Appeal_Sort desc, dbo.vBoCsContact.LastName, dbo.vBoCsContact.FirstName; ");
                    SqlDataAdapter dscmd = new SqlDataAdapter(query.ToString(), cnn);
                    DataTable dt = new DataTable();
                    dscmd.Fill(dt);
                    query.Clear();

                    try
                    {

                        oSheet = (Excel._Worksheet)oXL.Worksheets.Add();
                        oSheet.Name = dt.Rows[0]["Appeal"].ToString().Replace(" ", "").
                            Replace("  ", "").Replace("/", "").
                                Replace("\\", "").Replace("*", "");


                        for (i = 0; i <= dt.Rows.Count - 1; i++)
                        {
                            for (j = 0; j <= dt.Columns.Count - 1; j++)
                            {
                                data = dt.Rows[i].ItemArray[j].ToString();
                                oSheet.Cells[i + 1, j + 1] = data;

                            }
                        }

                    }

                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        GC.Collect();
                    }
                }


                oWB.SaveAs(@"H:\4862appeals1.xlsx",
                   AccessMode: Excel.XlSaveAsAccessMode.xlShared);

                oWB.Close(true, misValue, misValue);
                oXL.Quit();

                label1.Text = "Click button to start";     
            }
        }
    }

【讨论】:

    【解决方案3】:

    使用 EPPlus NuGet 包,it's very easy

    public class TestObject
    {
        public int Col1 { get; set; }
        public int Col2 { get; set; }
        public string Col3 { get; set; }
        public DateTime Col4 { get; set; }
    }
    
    [TestMethod]
    public void LoadFromCollection_MemberList_Test()
    {
        //https://stackoverflow.com/questions/32587834/epplus-loadfromcollection-text-converted-to-number/32590626#32590626
    
        var TestObjectList = new List<TestObject>();
        for (var i = 0; i < 10; i++)
            TestObjectList.Add(new TestObject {Col1 = i, Col2 = i*10, Col3 = (i*10) + "E4"});
    
        //Create a test file
        var fi = new FileInfo(@"c:\temp\LoadFromCollection_MemberList_Test.xlsx");
        if (fi.Exists)
            fi.Delete();
    
        using (var pck = new ExcelPackage(fi))
        {
            //Do NOT include Col1
            var mi = typeof (TestObject)
                .GetProperties()
                .Where(pi => pi.Name != "Col1")
                .Select(pi => (MemberInfo)pi)
                .ToArray();
    
            var worksheet = pck.Workbook.Worksheets.Add("Sheet1");
            worksheet.Cells.LoadFromCollection(
                TestObjectList
                , true
                , TableStyles.Dark1
                , BindingFlags.Public| BindingFlags.Instance
                , mi);
    
            pck.Save();
        }
    }
    

    请注意 Col1 不在输出中:

    【讨论】:

      猜你喜欢
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      相关资源
      最近更新 更多