【发布时间】: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);
}
}
}
【问题讨论】:
-
不是直接的答案,而是一种可能的方法..您可以尝试使用 ClosedXML 来使用 Excel:jwcooney.com/2015/10/08/…stackoverflow.com/questions/8207869/…
-
这能回答你的问题吗? How to export DataTable to Excel
标签: c# sql-server excel winforms