Read Data from Excel Worksheet in c#? - c#

I need some way to read worksheets from an Excel file, then select what it's important, and put all the Data in a Database.
It's a job for one time only. It's an old excel file with information, that have to be passed to a Database, and which will work with an application that i have developed.
I saw many examples but i am not understanding well how it works, and which way is the best to do this type of work.
My idea is to develop some application in c# that to this process.

LINQ may work and would be preferable for a relatively simple table.
A traditional approach would be to use COM Interop. Here's a Microsoft page about to work with Excel using COM interop (it is for spreadsheet creation, but the principles are the same - just use different API methods to open and read data):
http://msdn.microsoft.com/en-us/library/ms173186(v=vs.80).aspx

I strongly suggest using a linq provider to connect to excel. This should make it very easy to query for the information you are looking for. Once you have it, inserting into the database should be easy.
http://code.google.com/p/linqtoexcel/

I've used this before and it works well.
http://exceldatareader.codeplex.com/
had an example handy...
using (FileStream fileStream = File.Open(inputFilenames[0], FileMode.Open, FileAccess.Read))
{
IExcelDataReader excelReader;
if (Path.GetExtension(inputFilenames[0]) == ".xls")
excelReader = Factory.CreateReader(fileStream, ExcelFileType.Binary);
else
excelReader = Factory.CreateReader(fileStream, ExcelFileType.OpenXml);
excelReader.NextResult();
while (excelReader.Name != this.Worksheet)
excelReader.NextResult();
while (excelReader.Read())
{
if (FirstRowHasColumnNames)
{
FirstRowHasColumnNames = false;
}
else
{
//do stuff
var test = GetColumnData(excelReader, 1);
}
}
this.Save(outputFilename);
}

Read Data from Excel Worksheet in c#? I got the Exact solution here visit
http://microsoftdotnetsolutions.blogspot.in/2012/12/get-excel-sheet-data.html

Related

How do create and make user download an Excel file from variable data in arrays?

I'm working on a project in .NET Core 1.1, and now I have to give the possibility to the user of downloading an Excel file which data is dependant on parameters chosen by the user, so the Excel should be created in the moment when the user clicks the "Export to Excel" button and downloaded.
I've been searching on the internet but I haven't gotten any clear answers to be honest. I guess I will have to use the Open XML SDK, but in order to create it in memory and such, I don't have enough knowledge.
To sum up, I have data in arrays, and I would like to be able, in the moment the user clicks a button, create the excel virtually with the data previously stored in arrays and then download it in the users browser.
Do you also want to show your data before download? Maybe you can use DataTables:
DataTables is a plug-in for the jQuery Javascript library. It is a
highly flexible tool, built upon the foundations of progressive
enhancement, that adds all of these advanced features to any HTML
table.
Pagination Previous, next and page navigation. Instant search Filter
results by text search.
using NPOI https://github.com/tonyqus/npoi
something in the line of this:
void safearrayAsExcel(object[,] rows,string filename){
var workbook = new HSSFWorkbook();
var sheet = workbook.CreateSheet("New Sheet");
for(int i = 0; i < rows.length;i++)
{
var row sheet.CreateRow(i);
for(int j = 0; j < row.length;j++)
row .CreateCell(j).SetCellValue(rows[i,j]);
}
FileStream fileOut = new FileStream(fileName, FileMode.Create);
workbook.Write(fileOut);
}
you can ofcourse use a memorystream instead of filestream and do whatever you want with the generated excel
use HSSFWorkbook for xls format. and XSSFWorkbook for xlsx format.
i dont completely know about compatibliy issues with .net core 1.1 and .net standard 2.0 but there should be a way go get it work

EPPlus with OpenXML and streams

I am trying to automate a Powerpoint presentation. I am using OpenXML to navigate the powerpoint presentation up to the point that I find the Excel linked to a chart. Now I want to use EPPlus to load a datatable into one of the worksheets (because EPPlus has a simple LoadFromDataTable function whereas I think I would have to write lots of code to use OpenXML).
So my problem is this.
I have a PresentationDocument in memory. And I have navigated to the particular chart that I want to manipulate via:
doc.PresentationPart.SlideParts.ElementAt(0).ChartParts.ElementAt(0)
I get the Excel part using:
var stream = chartpart.EmbeddedPackagePart.GetStream()
Then I tried:
using(var pck = new ExcelPackage(stream)) {
`do stuff;
`pck.Save();
}
and then at the end I do a doc.PresentationPart.Presentation.Save but this hasn't changed the Presentation. I can change it using OpenXML instead with:
using (var xl = Spreadsheet.Document.Open(stream, true))
{
`do stuff;
`xl.Close();
}
With everything else the same. So I guess either xl.Close() is doing stuff that pck.Save() isn't or I am using the stream incorrectly - can anyone advise?

.NET C# - Importing Excel File - Sheet Name!

I'm using the NPOI Library to import some data from an excel sheet to my database.
One early issue I'm curious about, is typically, to begin, you would have something like this:
snippet
using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs);
HSSFSheet sheet = templateWorkbook.GetSheet("Sales");
My query is, what happens when the name of the worksheet is different each time, e.g. I plan to import sales data, and the sheets within the workbooks I receive from suppliers are titled by date.
Is there any way that you can specify GetSheet(); to just get the first sheet in the workbook?
Any pointers would be much appreciated,
thanks guys :)
Without trying it out I'd assume that you're looking for getSheetAt.
So it would be:
HSSFSheet sheet = templateWorkbook.GetSheetAt(0);

C# Read Excel using late binding

Hi
I have not used late binding before but it would seem to be the solution, if only I could find a concise example!
Or may be it's not the solution but I'm sure you guys will know!
I need to fill a dropdown combbox list from a column in excel reading down to the first blank cell. the solution needs to work with excel 2003 and above some PCs never have had 2003 install only office 2010 other have been upgraded from 2003 and some are still on 2003!
I need a solution that works on all of the above.
So I'm looking into late binding is this the correct way to go? would Linq help!?
Its a clasic windows Form app using .Net 4.
I thought I would write a method that takes the file name and path and returns a list which I would then assign to the combobox.
But being new I'm not getting pass go!
Any help/examples PLEASE
It sounds like you're looking at using COM interop/automation with the Excel application installed on client machines.
If your sole requirement is to extract data from an Excel file, you'll be better off using a library that can simply read data out of the file itself, rather than launching the Excel process in the background.
It is faster, cleaner, and more testable.
I've used NPOI for .xls files (and there are certainly others), and there are LOTS of options for .xlsx files. This SO question is about creating a file, but any of the suggested libraries can of course read files as well.
The only time I'd use COM automation is to interact with a running instance of Excel.
Edit (in response to comments)
Here is a sample of getting the values of column B as strings:
using System;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var stream = new FileStream(#"c:\my_workbook.xls", FileMode.Open);
var workbook = new HSSFWorkbook(stream);
stream.Close();
var sheet = workbook.GetSheet("My Sheet Name");
var row_enumerator = sheet.GetRowEnumerator();
while (row_enumerator.MoveNext())
{
var row = (Row)row_enumerator.Current;
var cell = row.GetCell(1); // in Excel, indexes are 1-based; in NPOI the indexes are 0-based
Console.WriteLine(cell.StringCellValue);
}
Console.ReadKey();
}
}
}

Saving Excel 2007 documents

In .NET C# I'm trying to open an Excel template, add some data and save it as a new document. I'm trying to use the OpenXML document format. I can't seem to find any guidance on how to do this. Seems like all the documentation talks about how to write various parts to the Package but I can't find anything on what to do when you're done and want to save it.
Anyone know where I can find this information? I must be thinking about this incorrectly because I'm not finding anything useful on what seems to be very basic.
Thanks
ExcelPackage works pretty good for that. It hasn't been worked on by the primary author I dont think for a little while but it has a good following of people on its forum that work any issues out.
FileInfo template = new FileInfo(Path.GetDirectoryName(Application.ExecutablePath)+"\\Template.xlsx");
try
{
using (ExcelPackage xlPackage = new ExcelPackage(strFileName,template))
{
//Enable DEBUG mode to create the xl folder (equlivant to expanding a xlsx.zip file)
//xlPackage.DebugMode = true;
ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets["Sheet1"];
worksheet.Name = WorkSheetName;
foreach (DataRow row in dt.Rows)
{
int c = 1;
if (r > startRow) worksheet.InsertRow(r);
// our query has the columns in the right order, so simply
// iterate through the columns
foreach (DataColumn col in dt.Columns)
{
if (row[col].ToString() != null)
{
worksheet.Cell(r, c).Value = colValue;
worksheet.Column(c).Width = 10;
}
c++;
}
r++;
}
// change the sheet view to show it in page layout mode
worksheet.View.PageLayoutView = false;
// save our new workbook and we are done!
xlPackage.Save();
xlPackage.Dispose();
}
}
Accessing Open XML / SpreadsheetML documents is far from a trivial exercise. The specification is large and complex. The "Open XML SDK" (google it) definitely helps, but still requires some knowledge of the Open XML standard to get much done.
SpreadsheetGear for .NET has an API similar to Excel and can read and write Excel Open XML (xlsx) documents as well as Excel 97-2003 (xls) documents.
You can see some SpreadsheetGear samples here and download a free trial here.
Disclaimer: I own SpreadsheetGear LLC

Categories

Resources