Skip to content

Instantly share code, notes, and snippets.

@Tomamais
Created April 29, 2024 18:32
Show Gist options
  • Save Tomamais/5d64204f887c8467ec671c899bea9e69 to your computer and use it in GitHub Desktop.
Save Tomamais/5d64204f887c8467ec671c899bea9e69 to your computer and use it in GitHub Desktop.
using System;
using Oracle.ManagedDataAccess.Client;
using OfficeOpenXml;
using System.IO;
namespace OracleConnectionExample
{
class Program
{
static void Main(string[] args)
{
// Oracle database connection string
string connString = "User Id=YourUsername;Password=YourPassword;Data Source=YourOracleDB;";
// SQL query with parameter
string sqlQuery = "SELECT * FROM YourTable WHERE ColumnName = :paramValue";
// Parameter value
string paramValue = "example_parameter_value";
// Create Oracle connection and command objects
using (OracleConnection conn = new OracleConnection(connString))
{
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
// Add parameter to the command
cmd.Parameters.Add(":paramValue", OracleDbType.Varchar2).Value = paramValue;
try
{
// Open the connection
conn.Open();
// Create Excel package and worksheet
ExcelPackage package = new ExcelPackage();
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Data");
// Execute the query and fill Excel worksheet
using (OracleDataReader reader = cmd.ExecuteReader())
{
int row = 1;
while (reader.Read())
{
// Fill Excel worksheet with data
for (int col = 0; col < reader.FieldCount; col++)
{
worksheet.Cells[row, col + 1].Value = reader[col];
}
row++;
}
}
// Save Excel file
string excelFilePath = @"C:\Path\To\Your\File.xlsx";
File.WriteAllBytes(excelFilePath, package.GetAsByteArray());
Console.WriteLine("Data exported to Excel successfully.");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment