Currently I'm working with ExcelLibrary.dll
The problem with ExcelLibrary is that it makes corrupt excel files if data is less or excel size is less than 6kB.
So I am switching to EPPlus dll.
Currently my code is:
DataSet dsNewDataSet = new DataSet();
string tempTbl = "SELECT * FROM EngineersDetail ORDER BY 3,1";
SqlCommand commandOpen = new SqlCommand(tempTbl, conSql);
SqlDataAdapter adpUpdRow = new SqlDataAdapter();
adpUpdRow.SelectCommand = commandOpen;
adpUpdRow.Fill(dsNewDataSet , "table");
//Create Excel worksheet from the data sets
ExcelLibrary.DataSetHelper.CreateWorkbook("C:/Engineer-wise Performance Report/Engineer-wise Performance Report.xls", dsNewDataSet );
This is a sample code. It selects data from the table EngineersDetail and fill in the DataSet dsNewDataSet, which then dumps data into an excel file.
I later retrieve this excel file generated to send as an attachment in a mail.
Now I want to shift this code completely to EPPlus library code.
Related
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#?
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.
The problem can be divided into two sub problems
Getting Data into c# from postgres.
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.!!!
I have a requirement to generate output report in Excel format and open the same on the screen when the processing is complete. But in this case, it should not save the report on the drive anywhere and only open on the screen.
I tried to use ADO using OLEDB but it always generates file before writing anything to it.
This is what I have tried so far.
using (OleDbConnection con = new OleDbConnection(connString))
{
try
{
con.Open();
}
catch (InvalidOperationException invalidEx)
{
//Exception handling
}
// Create table for excel structure
StringBuilder strSQL = new StringBuilder();
strSQL.Append("CREATE TABLE [" + tableName + "]([TITLE] text,[SURNAME] text,[STATUS] text)");
// Define file columns
StringBuilder strfield = new StringBuilder();
strfield.Append("[TITLE],[SURNAME],[STATUS]");
OleDbCommand cmd = new OleDbCommand(strSQL.ToString(), con);
cmd.ExecuteNonQuery(); // This creates the table
//Actual row for creating and insering row - logic not shown completely
cmd.CommandText = strSQL.Append(" insert into [" + tableName + "]( ")
.Append(strfield.ToString())
.Append(") values (").Append(strvalue).Append(")").ToString();
success = cmd.ExecuteNonQuery();
But this always creates the file first which I do not want.
Please advise if anyone has worked on the similar requirement. Thanks.
Ok, first off use ADO (a database access technology) to try and create a spreadsheet is bizarre, possibly doable, but definitely not easy.
Secondly you're saying create a spreadsheet and open it, without creating a file, this means that you'll also have to create ALL the functionality to open, parse, format and display spreadsheets (basically recreate Excel!)...as Excel cannot do this for you.
So I would question the "generate output report in Excel format" requirement, does this really mean "display in a grid"? Or is it "display in a grid that allows formatting, totalling?"
If it the Excel format really is a requirement, then the only thing I can suggest is you will have to create a temporary Excel file, then delete it after you've displayed it.
I would look at the ClosedXML library that really simplifies the use of OpenXML to create xlsx spreadsheets.
Perhaps this Microsoft Article will help: How to: Open a spreadsheet document from a stream (Open XML SDK)
I have a huge collection of Excel files. there are many information privite and my client want to store it in database. And later they can use the data in the database to rebuild all the Excel report. So do you have any idea to achieve that? what if I convert Excel to byte stream to store?
I know that if i put Excel to byte stream, will use more time and space to handle like formats and other thing, and stupid to do that. So I would like other way to store the data?
As Uriel_SVK said, Interop.Excel should be easy to achieve that. But if you just wish to store datas, can also have a try with Oledb.
string myConnection ="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\test.xlsx;Extended Properties="Excel 12.0 ;HDR=YES";
OleDbConnection conn = new OleDbConnection(connstr);
string strSQL = "SELECT * FROM [Sheet$]";
OleDbCommand cmd = new OleDbCommand(strSQL, conn);
DataSet dataset = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(dataset);
GridViewXYZ.DataSource = dataset;
GridViewXYZ.DataBind();
Are you constrained to using C#? Certain versions of SQL Server offer DTS or SSIS services for moving data in and out of the database from various sources/destinations such as Excel files. Oracle has something similar in OWB.
You can use Jet OleDB.
The sheet will be the tables and the workbook will be the database. You can use SQl query to produce the data what you want and save it on a datatable/dataset
I am working on window application and I want to export data from datagridview to spread sheet, How can I export it without using Microsoft Excel dll.
I searched about openoffice but could not found a proper solution for window form.
There are certain third party libraries, such as Essential Studio XlsIO (.NET library).
Samples: XlsIO
I used google Excel library for this.
Add Excel library to your solution and use this code.
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt1.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt1 = Extensions.AsDataTable(objEntityDataModel.smme_campaign_report(campId));
ds.Tables.Add(dt1);
//set the campaign name and create word file
ExcelLibrary.DataSetHelper.CreateWorkbook(#"d:\\" + campaignName + ".xlsx", ds);
I want to load a column in excel into a selectable dropdown menu using c#. I have access to the file, and can load the file in C#, but am not sure how to implement what I want. Suggestions? (I'm using Visual Studio 2008)
You can use the OleDb Managed Data Provider to read an Excel spreadsheet using ADO.NET just like you would with a database.
using System.Data.OleDb;
DataTable dt = new DataTable();
string connString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\Book1.xls;Extended Properties='Excel 8.0;HDR=NO'";
using (OleDbConnection conn = new OleDbConnection(connString))
{
conn.Open();
//Where [F1] = column one, [F2] = column two etc, etc.
OleDbCommand selectCommand = new OleDbCommand("select [F1] AS [id] from [Sheet1$]",conn);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = selectCommand;
adapter.Fill(dt);
}
listBox1.DataSource = dt;
listBox1.DisplayMember = "id";
You could implement a PIA solution something like this (assuming 5 items in column "A" of the first worksheet):
using Excel = Microsoft.Office.Interop.Excel;
...
worksheet = workbook.Worksheets[1] as Excel.Worksheet;
Excel.Range range;
range = worksheet.get_Range("A1", "A5") as Excel.Range;
foreach (Excel.Range cell in range.Cells)
{
myComboBox.Items.Add(cell.Value2 as string);
}
If you don't know the exact number if items in the dropdown at runtime, you will need to search the range to find the end; check out this sample here.
This sample uses the Office 2007 PIAs, if you are using an older version the syntax should be very close but might vary a bit.
As far as I know you only have a couple of options:
Primary Interop Assemblies (PIA) that let you read and write from the Excel object model.
Building a Visual Studio Tools for Office (VSTO) solution, which effectively lets you write 'code behind' for your Excel spreadsheet. Depending on what you are trying to achieve this can make sense if you are actually doing a lot of work within excel, and your current application is really just creating an extension to the spreadsheet UI.