0

I need to export Postgres DB (having around 20 tables) to excel using C#. I need to implement some logic on the data from DB and then need to export it. Any idea of how to export all data using c#?

2 Answers 2

3
using Npgsql;
using OfficeOpenXml;  // Nuget EPPlus
using System.IO;

EPPlus has a one-step method to export a data table into a spreadsheet, so if you leveraged this, you should be able to loop through your queries and export each one to a unique sheet.

Something like this (untested but should be 99% there) should do the trick:

FileInfo fi = new FileInfo("foo.xlsx");
ExcelPackage excel = new ExcelPackage(fi);

int sheet = 1;

foreach (string sql in sqlQueries)
{
    DataTable dt = new DataTable();
    NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
    NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
    da.Fill(dt);

    ExcelWorksheet ws = excel.Workbook.Worksheets.Add(string.Format("Sheet{0}", sheet++));
    ws.Cells["A1"].LoadFromDataTable(dt, true);
}

excel.Save();

Of course, I'd recommend some refinements to deal with datatypes, formatting and the like, but this is the basic construct.

Also, of course, use the IDisposable using liberally.

Sign up to request clarification or add additional context in comments.

Comments

1

The problem can be divided into two sub problems

  1. Getting Data into c# from postgres.
  2. pushing that data into excel.

Now solving a problem at a time

Here is a good article on working with postgres using c#

once you have you data in c# you can use any one of many libraries available for working with Excel using c#

One of them is NPOI

Here is one with example

Happy Coding.!!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.