Loading excel column data using C# in a dropdown menu - c#

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.

Related

To export Postgres DB to excel using c#

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.!!!

Writing to excel using OleDb

I am attempting to export rows of data from sql to excel but my Insert Command seems to fail every time. I have spent a good deal of time trying to create this but I have finally run up against the wall.
The excel document is one that is generated by the IRS and we are not aloud to modify anything above row 16. Row 16 is the header row, and everything below that needs to be the data from sql. The header names all have spaces in them, and that seems to be where I am running into trouble.
Starting at row 16 the column names are:
Attendee First Name, Attendee Last Name, Attendee PTIN, Program Number, CE Hours Awarded Program, Completion Date
This is how I am attempting to write to excel
private void GenerateReport()
{
FileInfo xlsFileInfo = new FileInfo(Server.MapPath(CE_REPORTS_PATH + CE_PTIN_TEMPLATE + EXTENSION));
string connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes'", xlsFileInfo.FullName);
//create connection
OleDbConnection oleDBConnection = new OleDbConnection(connectionString);
oleDBConnection.Open();
//create the adapter with the select to get
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$A16:F16]", oleDBConnection);
// Create the dataset and fill it by using the adapter.
DataTable dataTable = new DataTable();
adapter.FillSchema(dataTable, SchemaType.Source);
adapter.Fill(dataTable);
string[] colNames = new string[dataTable.Columns.Count];
string[] colParms = new string[dataTable.Columns.Count];
for (int i = 0; i < dataTable.Columns.Count; i++)
{
colNames[i] = String.Format("[{0}]", dataTable.Columns[i].ColumnName);
colParms[i] = "?";
}
// Create Insert Command
adapter.InsertCommand = new OleDbCommand(String.Format("INSERT INTO [Sheet1$] ({0}) values ({1})", string.Join(",", colNames), string.Join(",", colParms)), oleDBConnection);
// Create Paramaters
for (int i = 0; i < dataTable.Columns.Count; i++)
{
OleDbParameter param = new OleDbParameter(String.Format("#[{0}]", dataTable.Columns[i].ColumnName), OleDbType.Char, 255, dataTable.Columns[i].ColumnName);
adapter.InsertCommand.Parameters.Add(param);
}
// create a new row
DataRow newCERecord = dataTable.NewRow();
// populate row with test data
for (int i = 0; i < dataTable.Columns.Count; i++)
{
newCERecord[i] = "new Data";
}
dataTable.Rows.Add(newCERecord);
// Call update on the adapter to save all the changes to the dataset
adapter.Update(dataTable);
oleDBConnection.Close();
}
The error I get happens when adapter.Update(dataTable) is called and is as follows
$exception {"The INSERT INTO statement contains the following unknown field name: 'Attendee First Name'. Make sure you have typed the name correctly, and try the operation again."} System.Exception {System.Data.OleDb.OleDbException}
This is frustrating because I pull each field directly from the column name as gotten by colNames[i] = String.Format("[{0}]", dataTable.Columns[i].ColumnName). I discovered I needed the [] to account for the spaces in the column names, but at this point I am not sure what the problem is. When I look at the excel file everything seems correct to me.
I actually found a Microsoft article for you that has the entire code done - you can likely copy & paste whichever solution you like most. Here's the link:
http://support.microsoft.com/kb/306023
It seems like the one with CopyRecordset is your easiest approach, although they do explain the one I mentioned (using a tab-delimited file).
Edit: Here's my original answer for the sake of completeness. See the link above instead for more details and for a possible better solution.
This is not an answer to your question but a suggestion to change your approach (if you can). Excel tends to be very slow when adding data through COM calls and I assume OleDB uses COM internally. In my experience the fastest (and coincidentally the least painful way) to output data to Excel was to generate a tab-separated text file with all the data and then just import the file into Excel and use COM interop to perform any formatting on the sheet. When I generated Excel reports this way, most of my reports used to be generated almost 100x faster than using the Excel COM object model. (I don't know if this would be the same for OleDB calls, since I've never used OleDB with Excel but I'd be willing to bet the OleDB adapter uses COM internally.)
This would also take care of your embedded space problem since tab would be the column separator.
In your particular situation, I'd import the text file into Excel into a new sheet and then copy & paste it into the IRS sheet, at the right location. When done, the temporary sheet can be deleted.

Export to excel without using the com object

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.

Import Excel to database in C#.NET

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

Export excel using openoffice in c# win form

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);

Categories

Resources