I'm exporting a dataset to an Excel sheet, but I don't want to use the COM of Excel, because it takes a lot of time.
I need a method that exports to Excel without using the MS Office Interop, and I need to load the method using an empty Excel template so that the new Excel sheet has the same format.
You could reach an excel file and update its contents using ADO.NET and the Jet OleDbProvider
string con = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your_path\test.xls;Extended Properties='Excel 8.0;HDR=No;'";
using(OleDbConnection c = new OleDbConnection(con))
{
c.Open();
string commandString = "Insert into [Sheet1$] (F1, F2, F3) values('F1Text', 'F2Text', 'F3Text')" ;
using(OleDbCommand cmd = new OleDbCommand(commandString))
{
cmd.Connection = c;
cmd.ExecuteNonQuery();
}
}
I use EPPlus. Available via Nuget and LGPL licensed. Let's you create and manage xlsx spreadsheets using OOXML.
I would look into something like this xlslinq
But you can also use this library as it will export it to a dataset
I would suggest using the Open XML SDK 2.0
You will be able to do everything you requested and on top of that it is very fast.
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 am using c# windows forms application where I am using MySQL DB, my requirement is to export complete table data in Excel format. Please tell me how it is possible.
I am using following code to save my data in MYSQL DB
private void insert_data()
{
string MyConnection2= "datasource=localhost;port=3306;username=abc;password=xyz";
string Query = "";
reset_data();
Query = "INSERT INTO test_data.display_only(Article_ID ,Article_Name ,Manufacturer,Article_Quantity) SELECT Article_ID,Article_Name ,Manufacturer,Article_Quantity FROM _data.entered_items";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
MessageBox.Show("Data Updated");
while (MyReader2.Read())
{
}
MyConn2.Close();
}
You'll find plenty of ways to export database to excel by a simple Google search. For EX: You can use excel.interop if Excel is installed: How to export databse to excel file. Other alternative ways without having Excel installed: Solutions to Export Data From Database to Excel in C# or export to excel using Open XML SDK.
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 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.