2009-02-05 63 views
0

我想閱讀一些excel文件並將其轉換爲我自己的excel模板。我想閱讀B coloumn每行。(B1,B2,B3 ...正在這樣做。) 如果這個色號中有一個數字,在B3中有數字像「1,2,3,4,5,6,7,8,9」比我會得到這整行,並將其數組[i]。如果有「5」數字在B4比它會得到這整行,並把它給一個數組[i]。如果相關行中沒有數字,它將contiune到下一行。它將contiune讀取excel文件的結尾。我想要這個數組並寫入一個新的Excel文件。這就是我想要的,請幫助我的示例代碼。從Excel文件中讀取特定的Coloumns用C#

+0

這是Office 2003以及更早或Office 2007? – hova 2009-02-05 18:47:11

回答

3
  1. Download並在計算機上安裝Office 2003的主互操作程序集
  2. 創建一個Visual Studio項目並從GAC添加對'Microsoft.Office.Interop.Excel.dll'的引用。
  3. 現在你可以這樣寫代碼從任何Excelfile

示例讀取數據:

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); 
} 
+0

我會嘗試這一點。但這不是控制如果B1 B2 B3 ....是數字或Null ..如果它們爲空或不是數字,它會得到下一行。如果你想我可以發送我的模板excel文件和非編輯的excel文件。 – 2009-02-06 12:27:18