I'm trying to move data from SQL Server 2012 to Excel 2010 via a C# form using WinForms. The data I have contains a column called "Appeal" for which I would like to create separate worksheets inside an excel workbook. I would like to label the tabs with the name of the "Appeal". The part I can't seem to get is actually putting the data into the related tabs that I just created and labeled. Can anyone with more experience help me out? Note the table and values are a simplified version of the actual table.
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);
}
}
}