Export Two tables in SQL server to Single Excel sheet using C#Add a column with a default value to an existing table in SQL ServerHow to return only the Date from a SQL Server DateTime datatypeHow to check if a column exists in a SQL Server table?How to create Excel (.XLS and .XLSX) file in C# without installing Ms Office?Check if table exists in SQL ServerHow to concatenate text from multiple rows into a single text string in SQL server?LEFT JOIN vs. LEFT OUTER JOIN in SQL ServerWhat do two question marks together mean in C#?Inserting multiple rows in a single SQL query?How do I UPDATE from a SELECT in SQL Server?

Contradiction proof for inequality of P and NP?

Why did C use the -> operator instead of reusing the . operator?

Is there metaphorical meaning of "aus der Haft entlassen"?

How to have a sharp product image?

Co-worker works way more than he should

How do I deal with a coworker that keeps asking to make small superficial changes to a report, and it is seriously triggering my anxiety?

Where was the County of Thurn und Taxis located?

How to keep bees out of canned beverages?

Is there any pythonic way to find average of specific tuple elements in array?

Why do distances seem to matter in the Foundation world?

Are there moral objections to a life motivated purely by money? How to sway a person from this lifestyle?

How can I wire a 9-position switch so that each position turns on one more LED than the one before?

Is Electric Central Heating worth it if using Solar Panels?

Double-nominative constructions and “von”

I preordered a game on my Xbox while on the home screen of my friend's account. Which of us owns the game?

How much of a wave function must reside inside event horizon for it to be consumed by the black hole?

"The cow" OR "a cow" OR "cows" in this context

How do I produce this Greek letter koppa: Ϟ in pdfLaTeX?

How to not starve gigantic beasts

Combinatorics problem, right solution?

Crossed out red box fitting tightly around image

Multiple options vs single option UI

How bug prioritization works in agile projects vs non agile

Philosophical question on logistic regression: why isn't the optimal threshold value trained?



Export Two tables in SQL server to Single Excel sheet using C#


Add a column with a default value to an existing table in SQL ServerHow to return only the Date from a SQL Server DateTime datatypeHow to check if a column exists in a SQL Server table?How to create Excel (.XLS and .XLSX) file in C# without installing Ms Office?Check if table exists in SQL ServerHow to concatenate text from multiple rows into a single text string in SQL server?LEFT JOIN vs. LEFT OUTER JOIN in SQL ServerWhat do two question marks together mean in C#?Inserting multiple rows in a single SQL query?How do I UPDATE from a SELECT in SQL Server?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am new to C#... I am creating an application two tables in SQL server to a single Excel sheet. I export one table to excel successfully but I have no idea export 2nd table the same Excel sheet and the Two table are differently placed in the excel cells...so can't join the tables below my code Help me to solve this



class ExportToExcel


private Excel.Application app;
private Excel.Workbook workbook;
private Excel.Worksheet previousWorksheet;
private static string CONNECTION_STR = "Integrated Security=True";

public ExportToExcel()

this.app = null;
this.workbook = null;
this.previousWorksheet = null;
createDoc();


private void createDoc()


try

app = new Excel.Application();

app.Visible = false;
workbook = app.Workbooks.Add(1);



catch (Exception e)

Console.Write(e.ToString());


finally




public void shutDown()


try

workbook = null;

app.Quit();

catch (Exception e)


Console.Write(e.ToString());


finally




public void ExportTable(string query, string sheetName)


SqlConnection myConnection = new SqlConnection(CONNECTION_STR);
SqlDataReader myReader = null;

try


Excel.Worksheet oSheet = (Excel.Worksheet)workbook.Sheets.Add(Missing.Value, Missing.Value, 1, Excel.XlSheetType.xlWorksheet);
oSheet.Name = sheetName;
previousWorksheet = oSheet;
myConnection.Open();
SqlCommand myCommand = new SqlCommand(query, myConnection);
myReader = myCommand.ExecuteReader();

int columnCount = myReader.FieldCount;
int rowCounter = 3;
while (myReader.Read())


for (int n = 0; n < columnCount; n++)



addData(oSheet, rowCounter, n + 1, myReader[myReader.GetName(n)].ToString());


rowCounter++;





catch (Exception e)

Console.WriteLine(e.ToString());


finally

if (myReader != null && !myReader.IsClosed)


myReader.Close();


if (myConnection != null)


myConnection.Close();


myReader = null;
myConnection = null;





public void createHeaders(Excel.Worksheet worksheet, int row, int col, string htext)


worksheet.Cells[row, col] = htext;




public void addData(Excel.Worksheet worksheet, int row, int col, string data)


worksheet.Cells[row, col] = data;




public void SaveWorkbook()


String folderPath = "C:\My Files\";

if (!System.IO.Directory.Exists(folderPath))


System.IO.Directory.CreateDirectory(folderPath);


DateTime today = DateTime.Today;
string fileNameBase = today.ToString("dd-MMM-yyyy");
String fileName = today.ToString("dd-MMM-yyyy");
string ext = ".xlsx";
int counter = 1;

while (System.IO.File.Exists(folderPath + fileName + ext))


fileName = fileNameBase + counter;
counter++;


fileName = fileName + ext;

string filePath = folderPath + fileName;

try

workbook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);


catch (Exception e)

Console.WriteLine(e.ToString());





static void Main(string[] args)



ExportToExcel export = new ExportToExcel();
export.ExportTable("SELECT * from Table_1", "Data");
export.SaveWorkbook();
export.shutDown();
















share|improve this question
























  • You can't export to one worksheet two tables. You would need to join the two tables before exporting.

    – jdweng
    Mar 22 at 16:40











  • I can't Join Tables because of two tables are placed different places on the same sheet

    – Annisha
    Mar 22 at 16:51











  • Cant you use SSIS to export table data in same excel sheet and call this package using C#

    – Anusha Subashini
    Mar 22 at 17:34











  • You need to save the position of the last column that you inserted data into from the first table. Then you would add 1 to the saved position and insert the table 2 headers there and then insert below the table 2 headers.

    – Khal_Drogo
    Mar 22 at 18:50

















0















I am new to C#... I am creating an application two tables in SQL server to a single Excel sheet. I export one table to excel successfully but I have no idea export 2nd table the same Excel sheet and the Two table are differently placed in the excel cells...so can't join the tables below my code Help me to solve this



class ExportToExcel


private Excel.Application app;
private Excel.Workbook workbook;
private Excel.Worksheet previousWorksheet;
private static string CONNECTION_STR = "Integrated Security=True";

public ExportToExcel()

this.app = null;
this.workbook = null;
this.previousWorksheet = null;
createDoc();


private void createDoc()


try

app = new Excel.Application();

app.Visible = false;
workbook = app.Workbooks.Add(1);



catch (Exception e)

Console.Write(e.ToString());


finally




public void shutDown()


try

workbook = null;

app.Quit();

catch (Exception e)


Console.Write(e.ToString());


finally




public void ExportTable(string query, string sheetName)


SqlConnection myConnection = new SqlConnection(CONNECTION_STR);
SqlDataReader myReader = null;

try


Excel.Worksheet oSheet = (Excel.Worksheet)workbook.Sheets.Add(Missing.Value, Missing.Value, 1, Excel.XlSheetType.xlWorksheet);
oSheet.Name = sheetName;
previousWorksheet = oSheet;
myConnection.Open();
SqlCommand myCommand = new SqlCommand(query, myConnection);
myReader = myCommand.ExecuteReader();

int columnCount = myReader.FieldCount;
int rowCounter = 3;
while (myReader.Read())


for (int n = 0; n < columnCount; n++)



addData(oSheet, rowCounter, n + 1, myReader[myReader.GetName(n)].ToString());


rowCounter++;





catch (Exception e)

Console.WriteLine(e.ToString());


finally

if (myReader != null && !myReader.IsClosed)


myReader.Close();


if (myConnection != null)


myConnection.Close();


myReader = null;
myConnection = null;





public void createHeaders(Excel.Worksheet worksheet, int row, int col, string htext)


worksheet.Cells[row, col] = htext;




public void addData(Excel.Worksheet worksheet, int row, int col, string data)


worksheet.Cells[row, col] = data;




public void SaveWorkbook()


String folderPath = "C:\My Files\";

if (!System.IO.Directory.Exists(folderPath))


System.IO.Directory.CreateDirectory(folderPath);


DateTime today = DateTime.Today;
string fileNameBase = today.ToString("dd-MMM-yyyy");
String fileName = today.ToString("dd-MMM-yyyy");
string ext = ".xlsx";
int counter = 1;

while (System.IO.File.Exists(folderPath + fileName + ext))


fileName = fileNameBase + counter;
counter++;


fileName = fileName + ext;

string filePath = folderPath + fileName;

try

workbook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);


catch (Exception e)

Console.WriteLine(e.ToString());





static void Main(string[] args)



ExportToExcel export = new ExportToExcel();
export.ExportTable("SELECT * from Table_1", "Data");
export.SaveWorkbook();
export.shutDown();
















share|improve this question
























  • You can't export to one worksheet two tables. You would need to join the two tables before exporting.

    – jdweng
    Mar 22 at 16:40











  • I can't Join Tables because of two tables are placed different places on the same sheet

    – Annisha
    Mar 22 at 16:51











  • Cant you use SSIS to export table data in same excel sheet and call this package using C#

    – Anusha Subashini
    Mar 22 at 17:34











  • You need to save the position of the last column that you inserted data into from the first table. Then you would add 1 to the saved position and insert the table 2 headers there and then insert below the table 2 headers.

    – Khal_Drogo
    Mar 22 at 18:50













0












0








0








I am new to C#... I am creating an application two tables in SQL server to a single Excel sheet. I export one table to excel successfully but I have no idea export 2nd table the same Excel sheet and the Two table are differently placed in the excel cells...so can't join the tables below my code Help me to solve this



class ExportToExcel


private Excel.Application app;
private Excel.Workbook workbook;
private Excel.Worksheet previousWorksheet;
private static string CONNECTION_STR = "Integrated Security=True";

public ExportToExcel()

this.app = null;
this.workbook = null;
this.previousWorksheet = null;
createDoc();


private void createDoc()


try

app = new Excel.Application();

app.Visible = false;
workbook = app.Workbooks.Add(1);



catch (Exception e)

Console.Write(e.ToString());


finally




public void shutDown()


try

workbook = null;

app.Quit();

catch (Exception e)


Console.Write(e.ToString());


finally




public void ExportTable(string query, string sheetName)


SqlConnection myConnection = new SqlConnection(CONNECTION_STR);
SqlDataReader myReader = null;

try


Excel.Worksheet oSheet = (Excel.Worksheet)workbook.Sheets.Add(Missing.Value, Missing.Value, 1, Excel.XlSheetType.xlWorksheet);
oSheet.Name = sheetName;
previousWorksheet = oSheet;
myConnection.Open();
SqlCommand myCommand = new SqlCommand(query, myConnection);
myReader = myCommand.ExecuteReader();

int columnCount = myReader.FieldCount;
int rowCounter = 3;
while (myReader.Read())


for (int n = 0; n < columnCount; n++)



addData(oSheet, rowCounter, n + 1, myReader[myReader.GetName(n)].ToString());


rowCounter++;





catch (Exception e)

Console.WriteLine(e.ToString());


finally

if (myReader != null && !myReader.IsClosed)


myReader.Close();


if (myConnection != null)


myConnection.Close();


myReader = null;
myConnection = null;





public void createHeaders(Excel.Worksheet worksheet, int row, int col, string htext)


worksheet.Cells[row, col] = htext;




public void addData(Excel.Worksheet worksheet, int row, int col, string data)


worksheet.Cells[row, col] = data;




public void SaveWorkbook()


String folderPath = "C:\My Files\";

if (!System.IO.Directory.Exists(folderPath))


System.IO.Directory.CreateDirectory(folderPath);


DateTime today = DateTime.Today;
string fileNameBase = today.ToString("dd-MMM-yyyy");
String fileName = today.ToString("dd-MMM-yyyy");
string ext = ".xlsx";
int counter = 1;

while (System.IO.File.Exists(folderPath + fileName + ext))


fileName = fileNameBase + counter;
counter++;


fileName = fileName + ext;

string filePath = folderPath + fileName;

try

workbook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);


catch (Exception e)

Console.WriteLine(e.ToString());





static void Main(string[] args)



ExportToExcel export = new ExportToExcel();
export.ExportTable("SELECT * from Table_1", "Data");
export.SaveWorkbook();
export.shutDown();
















share|improve this question
















I am new to C#... I am creating an application two tables in SQL server to a single Excel sheet. I export one table to excel successfully but I have no idea export 2nd table the same Excel sheet and the Two table are differently placed in the excel cells...so can't join the tables below my code Help me to solve this



class ExportToExcel


private Excel.Application app;
private Excel.Workbook workbook;
private Excel.Worksheet previousWorksheet;
private static string CONNECTION_STR = "Integrated Security=True";

public ExportToExcel()

this.app = null;
this.workbook = null;
this.previousWorksheet = null;
createDoc();


private void createDoc()


try

app = new Excel.Application();

app.Visible = false;
workbook = app.Workbooks.Add(1);



catch (Exception e)

Console.Write(e.ToString());


finally




public void shutDown()


try

workbook = null;

app.Quit();

catch (Exception e)


Console.Write(e.ToString());


finally




public void ExportTable(string query, string sheetName)


SqlConnection myConnection = new SqlConnection(CONNECTION_STR);
SqlDataReader myReader = null;

try


Excel.Worksheet oSheet = (Excel.Worksheet)workbook.Sheets.Add(Missing.Value, Missing.Value, 1, Excel.XlSheetType.xlWorksheet);
oSheet.Name = sheetName;
previousWorksheet = oSheet;
myConnection.Open();
SqlCommand myCommand = new SqlCommand(query, myConnection);
myReader = myCommand.ExecuteReader();

int columnCount = myReader.FieldCount;
int rowCounter = 3;
while (myReader.Read())


for (int n = 0; n < columnCount; n++)



addData(oSheet, rowCounter, n + 1, myReader[myReader.GetName(n)].ToString());


rowCounter++;





catch (Exception e)

Console.WriteLine(e.ToString());


finally

if (myReader != null && !myReader.IsClosed)


myReader.Close();


if (myConnection != null)


myConnection.Close();


myReader = null;
myConnection = null;





public void createHeaders(Excel.Worksheet worksheet, int row, int col, string htext)


worksheet.Cells[row, col] = htext;




public void addData(Excel.Worksheet worksheet, int row, int col, string data)


worksheet.Cells[row, col] = data;




public void SaveWorkbook()


String folderPath = "C:\My Files\";

if (!System.IO.Directory.Exists(folderPath))


System.IO.Directory.CreateDirectory(folderPath);


DateTime today = DateTime.Today;
string fileNameBase = today.ToString("dd-MMM-yyyy");
String fileName = today.ToString("dd-MMM-yyyy");
string ext = ".xlsx";
int counter = 1;

while (System.IO.File.Exists(folderPath + fileName + ext))


fileName = fileNameBase + counter;
counter++;


fileName = fileName + ext;

string filePath = folderPath + fileName;

try

workbook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);


catch (Exception e)

Console.WriteLine(e.ToString());





static void Main(string[] args)



ExportToExcel export = new ExportToExcel();
export.ExportTable("SELECT * from Table_1", "Data");
export.SaveWorkbook();
export.shutDown();













c# sql-server excel console-application






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 16:49







Annisha

















asked Mar 22 at 16:33









AnnishaAnnisha

297




297












  • You can't export to one worksheet two tables. You would need to join the two tables before exporting.

    – jdweng
    Mar 22 at 16:40











  • I can't Join Tables because of two tables are placed different places on the same sheet

    – Annisha
    Mar 22 at 16:51











  • Cant you use SSIS to export table data in same excel sheet and call this package using C#

    – Anusha Subashini
    Mar 22 at 17:34











  • You need to save the position of the last column that you inserted data into from the first table. Then you would add 1 to the saved position and insert the table 2 headers there and then insert below the table 2 headers.

    – Khal_Drogo
    Mar 22 at 18:50

















  • You can't export to one worksheet two tables. You would need to join the two tables before exporting.

    – jdweng
    Mar 22 at 16:40











  • I can't Join Tables because of two tables are placed different places on the same sheet

    – Annisha
    Mar 22 at 16:51











  • Cant you use SSIS to export table data in same excel sheet and call this package using C#

    – Anusha Subashini
    Mar 22 at 17:34











  • You need to save the position of the last column that you inserted data into from the first table. Then you would add 1 to the saved position and insert the table 2 headers there and then insert below the table 2 headers.

    – Khal_Drogo
    Mar 22 at 18:50
















You can't export to one worksheet two tables. You would need to join the two tables before exporting.

– jdweng
Mar 22 at 16:40





You can't export to one worksheet two tables. You would need to join the two tables before exporting.

– jdweng
Mar 22 at 16:40













I can't Join Tables because of two tables are placed different places on the same sheet

– Annisha
Mar 22 at 16:51





I can't Join Tables because of two tables are placed different places on the same sheet

– Annisha
Mar 22 at 16:51













Cant you use SSIS to export table data in same excel sheet and call this package using C#

– Anusha Subashini
Mar 22 at 17:34





Cant you use SSIS to export table data in same excel sheet and call this package using C#

– Anusha Subashini
Mar 22 at 17:34













You need to save the position of the last column that you inserted data into from the first table. Then you would add 1 to the saved position and insert the table 2 headers there and then insert below the table 2 headers.

– Khal_Drogo
Mar 22 at 18:50





You need to save the position of the last column that you inserted data into from the first table. Then you would add 1 to the saved position and insert the table 2 headers there and then insert below the table 2 headers.

– Khal_Drogo
Mar 22 at 18:50












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55304058%2fexport-two-tables-in-sql-server-to-single-excel-sheet-using-c-sharp%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55304058%2fexport-two-tables-in-sql-server-to-single-excel-sheet-using-c-sharp%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript