Scenario : Download Script
You are working as C# or Dot Net Developer, You got this requirement “Create a program that should read the data from SQL server Table, create an Excel file with Date time and load data from SQL server Table". On each execution the new Excel file should be created. Once problem with requirement is that the C# program should be able to handle new columns dynamically or if columns dropped from Table, it should not fail and simply start creating file with available columns.
The below C# code can be used to create console application that can get the records from a table or view and write to an excel file. Every time you will execute the program, a new excel file will be created with date-time.
The below C# code can be used to create console application that can get the records from a table or view and write to an excel file. Every time you will execute the program, a new excel file will be created with date-time.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //added below name spaces using System.IO; using System.Data; using System.Data.OleDb; using System.Data.SqlClient; namespace TechBrothersIT.com_CSharp_Tutorial { class Program { static void Main(string[] args) { //the datetime and Log folder will be used for error log file in case error occured string datetime = DateTime.Now.ToString("yyyyMMddHHmmss"); string LogFolder = @"C:\Log\"; try { //Declare Variables //Provide the Excel file name you want to create string ExcelFileName = "Customer"; //Provide the folder in which Excel file should be created string FolderPath = @"C:\Destination\"; //Provide the table name or view name to Export records to Excel string TableName = "dbo.Customer"; //Provide the sheet name you like to create in excel file string SheetName = "Customer"; //Provide the Database Name in which table or view exists string DatabaseName = "TechbrothersIT"; //Provide the SQL Server Name string SQLServerName = "(local)"; ExcelFileName = ExcelFileName + "_" + datetime; OleDbConnection Excel_OLE_Con = new OleDbConnection(); OleDbCommand Excel_OLE_Cmd = new OleDbCommand(); //Construct ConnectionString for Excel string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + ExcelFileName + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\""; //drop Excel file if exists File.Delete(FolderPath + "\\" + ExcelFileName + ".xlsx"); //Create Connection to SQL Server Database from which you like to export tables to Excel SqlConnection SQLConnection = new SqlConnection(); SQLConnection.ConnectionString = "Data Source = "+SQLServerName+"; Initial Catalog =" + DatabaseName + "; " + "Integrated Security=true;"; //Load Data into DataTable from SQL ServerTable or view string queryString = "SELECT * from " + TableName; SqlDataAdapter adapter = new SqlDataAdapter(queryString, SQLConnection); DataSet ds = new DataSet(); adapter.Fill(ds); //Get Header Columns string TableColumns = ""; // Get the Column List from Data Table so can create Excel Sheet with Header foreach (DataTable table in ds.Tables) { foreach (DataColumn column in table.Columns) { TableColumns += column + "],["; } } // Replace most right comma from Columnlist TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(',')); TableColumns = TableColumns.Remove(TableColumns.Length - 2); //Use OLE DB Connection and Create Excel Sheet Excel_OLE_Con.ConnectionString = connstring; Excel_OLE_Con.Open(); Excel_OLE_Cmd.Connection = Excel_OLE_Con; Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")"; Excel_OLE_Cmd.ExecuteNonQuery(); //Write Data to Excel Sheet from DataTable dynamically foreach (DataTable table in ds.Tables) { String sqlCommandInsert = ""; String sqlCommandValue = ""; foreach (DataColumn dataColumn in table.Columns) { sqlCommandValue += dataColumn + "],["; } sqlCommandValue = "[" + sqlCommandValue.TrimEnd(','); sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2); sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES("; int columnCount = table.Columns.Count; foreach (DataRow row in table.Rows) { string columnvalues = ""; for (int i = 0; i < columnCount; i++) { int index = table.Rows.IndexOf(row); columnvalues += "'" + table.Rows[index].ItemArray[i] + "',"; } columnvalues = columnvalues.TrimEnd(','); var command = sqlCommandInsert + columnvalues + ")"; Excel_OLE_Cmd.CommandText = command; Excel_OLE_Cmd.ExecuteNonQuery(); } } Excel_OLE_Con.Close(); } catch (Exception exception) { // Create Log File for Errors using (StreamWriter sw = File.CreateText(LogFolder + "\\" + "ErrorLog_" + datetime + ".log")) { sw.WriteLine(exception.ToString()); } } } } }
I executed above program for dbo.Customer table and it created an excel file for me with
date-time.
How to Export Table or View records to Excel file in C# |
No comments:
Post a Comment