简体   繁体   中英

How can I read an Excel 2010 file in my C# code using a DLL?

UPDATE1:

I am using Excel 2010 and I've searched the web and found thousands upon thousands of ways to do this via win form, console, etc. But I can't find a way to do this via DLL. and none of the sample on-line is complete all in bit and pieces.

UPDATE END

I have looked and goggled but did not get the specific what i am looking for, as show below the excel sample sheet.

i'm looking a way to read and store the each cell data in a variable

i have started something like this:

Workbook workbook = open(@"C:\tmp\MyWorkbook.xls");
IWorksheet worksheet = workbook.Worksheets[0];
IRange a1 = worksheet.Cells["A1"];
object rawValue = a1.Value;
string formattedText = a1.Text;
Console.WriteLine("rawValue={0} formattedText={1}", rawValue, formattedText);

Excel表格

Excel.Sheets sheets = workbook.Worksheets;

Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);


System.Array myvalues;


Excel.Range range = worksheet.get_Range("A1", "E1".ToString());

myvalues = (System.Array)range.Cells.Value;

Your code can work with a couple changes.

One thing to remember is that Excel worksheets are 1-based, not 0-based (and use Worksheet instead of IWorksheet):

Worksheet worksheet = workbook.Worksheets[1];

And to get a range, it is easiest to call get_Range() on the worksheet object (and use Range instead of IRange):

Range a1 = worksheet.get_Range("A1");

With those two lines of code changed, your example will work fine.

UPDATE

Here is a "complete" example:

  1. Right-click your project in the solution explorer and click "Add Reference".
  2. Click on the COM tab and sort the list by Component Name. Find "Microsoft Excel 14.0 Object Library" in the list and select it. Click OK.
  3. In the code file where you want this to run, add a using Microsoft.Office.Interop.Excel;
  4. Use this code, which I've modified as little as possible from your example:

var excel = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = excel.Workbooks.Open(@"C:\tmp\MyWorkbook.xls");
Worksheet worksheet = workbook.Worksheets[1];
Range a1 = worksheet.get_Range("A1");
object rawValue = a1.Value;
string formattedText = a1.Text;
Console.WriteLine("rawValue={0} formattedText={1}", rawValue, formattedText);

If you don't want to be in a war with com components and registering dlls,

the best way to read excel is Excel Reader for .NET

I have been using it for so long time , and I can say it just works.

and excelReader.IsFirstRowAsColumnNames property makes everything easy. You can play your data within a dataset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM