[英]To export Postgres DB to excel using c#
I need to export Postgres DB (having around 20 tables) to excel using C#. 我需要使用C#将Postgres DB(大约有20个表)导出为excel。 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#?
关于如何使用C#导出所有数据的任何想法?
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. EPPlus具有将数据表导出到电子表格中的单步方法,因此,如果您利用此方法,则应该能够遍历查询并将每个查询导出到唯一的工作表中。
Something like this (untested but should be 99% there) should do the trick: 这样的事情(未经测试,但应该在那里达到99%)应该可以解决问题:
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. 当然,当然也
using
自由使用IDisposable。
The problem can be divided into two sub problems 该问题可以分为两个子问题
Now solving a problem at a time 现在一次解决一个问题
Here is a good article on working with postgres using c# 这是一篇有关使用C#使用Postgres的好文章
once you have you data in c# you can use any one of many libraries available for working with Excel using c# 在c#中获得数据后,就可以使用可用于使用c#的Excel的众多库中的任何一种
One of them is NPOI 其中之一就是NPOI
Here is one with example 这是一个例子
Happy Coding.!!! 快乐编码!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.