İbrahim Akgün
İbrahim Akgün

Reputation: 1567

Read specific columns from Excel files with C#

I want to read some Excel files and convert to my own Excel template. I want to read B column every line (B1,B2,B3... going like this).

If there is a number in this column; in B3 there is number like "1,2,3,4,5,6,7,8,9" then I'll get this whole line and take it to an array[i]. If there is "5" number in B4 then it'll get this whole line and take it to an array[i]. If there is no number in related line it will continue to next line.

It will continue to read end of the Excel file. And I want to take this array and write to a new Excel file.

Upvotes: 0

Views: 19127

Answers (2)

G S
G S

Reputation: 36818

  1. Download and install Office 2003 Primary Interop Assemblies on your computer
  2. Create a Visual studio Project and add a reference to 'Microsoft.Office.Interop.Excel.dll' from the GAC.
  3. Now you can write this code to read data from any Excelfile

Example:

using Excel = Microsoft.Office.Interop.Excel;

string pathOfExcelFile = "C:\\MyDataFile.xls";
Excel.Application excelApp = new Excel.Application();

excelApp.DisplayAlerts = false; //Don't want Excel to display error messageboxes  
Excel.Workbook workbook = excelApp.Workbooks.Open(pathOfExcelFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing,                                            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,                      Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //This opens the file
Excel.Worksheet sheet = workbook.get_Item(1); //Get the first sheet in the file
Excel.Range bColumn = sheet.get_Range("B", null);

List<string> dataItems = new List<string>();

foreach (object o in bColumn) 
{
     Excel.Range row = o as Excel.Range;
     string s = row.get_Value(null);
     dataItems.Add(s);
}

Upvotes: 2

lakshmanaraj
lakshmanaraj

Reputation: 4165

Please look at

http://support.microsoft.com/kb/306572

and

http://support.microsoft.com/kb/306023/EN-US/

You can implement your idea..

Upvotes: 0

Related Questions