reading data from excel sheet using C# - c#

how to read information inside an excel sheet using C# code......

You can either use Oledb
using System.Data;
using System.Data.OleDb;
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Book1.xls;Extended Properties=Excel 8.0");
OleDbDataAdapter da = new OleDbDataAdapter("select * from MyObject", con);
DataTable dt = new DataTable();
da.Fill(dt);
or you use Office Interop
this.openFileDialog1.FileName = "*.xls";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
openFileDialog1.FileName, 0, true, 5,
"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
0, true);
Excel.Sheets sheets = theWorkbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
for (int i = 1; i <= 10; i++)
{
Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString());
System.Array myvalues = (System.Array)range.Cells.Value;
string[] strArray = ConvertToStringArray(myvalues);
}
}

Programming with the C API in Excel 2010

If the data is tabular, use OleDB, otherwise you can use Automation to automate Excel and copy the values over to your app.
Or if it's the new XML format excel sheets you might be able to do it via the framework classes.
Info about Excel Automation: How to: Use COM Interop to Create an Excel Spreadsheet
Info about Excel via OleDB: How To Use ADO.NET to Retrieve and Modify Records in an Excel Workbook With Visual Basic .NET

Excel has an API for programming. You can use it to get range of data using c#. You can use something like:
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
oSheet.get_Range(RangeStart,RangeEnd)

NPOI is the way to go.
Using office interop requires that Office (and the right version) be installed on the machine your app is running on. If a web abb, that probably means no, and it's not robust enough for a production environment anyway. OLEDB has serious limitations, unless it's a one-off and the data is really simple I wouldn't use it.

Excel COM Interop - via Microsoft.Office.Interop.Excel + Microsoft.Office.Interop.Excel.Extensions
ADO.Net via OLEDB data provider for Excel.
Use of System.XML and/or Linq to XML and/or Open XML SDK (can also be used to create new books programmatically from scratch).
3rd party library such as NPOI.
3rd party vendor package such as spreadsheetgear

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

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.

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

What's the easiest way to create an Excel table with C#?

I have some tabular data that I'd like to turn into an Excel table.
Software available:
.NET 4 (C#)
Excel 2010 (using the Excel API is OK)
I prefer not to use any 3rd party libraries
Information about the data:
A couple million rows
5 columns, all strings (very simple and regular table structure)
In my script I'm currently using a nested List data structure but I can change that
Performance of the script is not critical
Searching online gives many results, and I'm confused whether I should use OleDb, ADO RecordSets, or something else. Some of these technologies seem like overkill for my scenario, and some seem like they might be obsolete.
What is the very simplest way to do this?
Edit: this is a one-time script I intend to run from my attended desktop.
Avoid using COM interop at all costs. Use a third-party API. Really. In fact, if you're doing this server-side, you virtually have to. There are plenty of free options. I highly recommend using EPPlus, but there are also enterprise-level solutions available. I've used EPPlus a fair amount, and it works great. Unlike interop, it allows you to generate Excel files without requiring Excel to be installed on the machine, which means you also don't have to worry about COM objects sticking around as background processes. Even with proper object disposal, the Excel processes don't always end.
http://epplus.codeplex.com/releases/view/42439
I know you said you want to avoid third-party libraries, but they really are the way to go. Microsoft does not recommend automating Office. It's really not meant to be automated anyway.
http://support.microsoft.com/kb/257757
However, you may want to reconsider inserting "a couple million rows" into a single spreadsheet.
Honoring your request to avoid 3rd party tools and using COM objects, here's how I'd do it.
Add reference to project: Com object
Microsoft Excel 11.0.
Top of module add:
using Microsoft.Office.Interop.Excel;
Add event logic like this:
private void DoThatExcelThing()
{
ApplicationClass myExcel;
try
{
myExcel = GetObject(,"Excel.Application")
}
catch (Exception ex)
{
myExcel = New ApplicationClass()
}
myExcel.Visible = true;
Workbook wb1 = myExcel.Workbooks.Add("");
Worksheet ws1 = (Worksheet)wb1.Worksheets[1];
//Read the connection string from App.Config
string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["NewConnString"].ConnectionString;
//Open a connection to the database
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = strConn;
myConn.Open();
//Establish the query
SqlCommand myCmd = new SqlCommand("select * from employees", myConn);
SqlDataReader myRdr = myCmd.ExecuteReader();
//Read the data and put into the spreadsheet.
int j = 3;
while (myRdr.Read())
{
for (int i=0 ; i < myRdr.FieldCount; i++)
{
ws1.Cells[j, i+1] = myRdr[i].ToString();
}
j++;
}
//Populate the column names
for (int i = 0; i < myRdr.FieldCount ; i++)
{
ws1.Cells[2, i+1] = myRdr.GetName(i);
}
myRdr.Close();
myConn.Close();
//Add some formatting
Range rng1 = ws1.get_Range("A1", "H1");
rng1.Font.Bold = true;
rng1.Font.ColorIndex = 3;
rng1.HorizontalAlignment = XlHAlign.xlHAlignCenter;
Range rng2 = ws1.get_Range("A2", "H50");
rng2.WrapText = false;
rng2.EntireColumn.AutoFit();
//Add a header row
ws1.get_Range("A1", "H1").EntireRow.Insert(XlInsertShiftDirection.xlShiftDown, Missing.Value);
ws1.Cells[1, 1] = "Employee Contact List";
Range rng3 = ws1.get_Range("A1", "H1");
rng3.Merge(Missing.Value);
rng3.Font.Size = 16;
rng3.Font.ColorIndex = 3;
rng3.Font.Underline = true;
rng3.Font.Bold = true;
rng3.VerticalAlignment = XlVAlign.xlVAlignCenter;
//Save and close
string strFileName = String.Format("Employees{0}.xlsx", DateTime.Now.ToString("HHmmss"));
System.IO.File.Delete(strFileName);
wb1.SaveAs(strFileName, XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
XlSaveAsAccessMode.xlExclusive, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value);
myExcel.Quit();
}
Some things for your consideration...
If this is a client side solution, there is nothing wrong with using Interops.
If this is a server side solution, Don't use Interops. Good alternative is OpenXML SDK from Microsoft if you don't want 3rd party solution. It's free. I believe the latest one has similar object model that Excel has. It's a lot faster, A LOT, in generating the workbook vs going the interops way which can bog down your server.
I once read that the easiest way to create an Excel table was to actualy write a HTML table, including its structure and data, and simply name the file .xls.
Excel will be able to convert it, but it will display a warning saying that the content does not match the extension.
I agree that a 3rd party dll would be cleaner than the com, but if you go the interop route...
Hands down the best way to populate an excel sheet is to first put the data in a 2 dimensional string array, then get an excel range object with the same dimensions and set it (range.set_value2(oarray) I think). Using any other method is hideously slow.
Also be sure you use the appropriate cleanup code in your finally block.
i implemented "export to Excel" with the ms-access-ole-db-driver that can also read and write excel files the follwoing way:
preparation (done once)
create an excel file that contains all (header, Formatting, formulas, diagrams) with an empty data area as a template to be filled
give the data area (including the headers) a name (ie "MyData")
Implementing export
copy template file to destination folder
open an oledb-database connection to the destination file
use sql to insert data
Example
Excel table with Named area "MyData"
Name, FamilyName, Birthday
open System.Data.OleDb.OleDbConnection
execute sql "Insert into MyData(Name, FamilyName, Birthday) values(...)"
I used this connection string
private const string FORMAT_EXCEL_CONNECT =
// #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR={1}""";
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR={1}""";
private static string GetExcelConnectionString(string excelFilePath, bool header)
{
return string.Format(FORMAT_EXCEL_CONNECT,
excelFilePath,
(header) ? "Yes" : "No"
);
}

Loading excel column data using C# in a dropdown menu

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.

Categories

Resources